代码之家  ›  专栏  ›  技术社区  ›  Narwhal

如何在UIView的子类中正确初始化传递的属性?

  •  1
  • Narwhal  · 技术社区  · 8 年前

    我有一个子类UIView,我想将属性传递给它。尽管我做了很多尝试,但我并没有真正理解初始化的所有元素。

    以下是我的代码的简化版本:

    class inputWithIncrementView : UIView, UITextFieldDelegate {
        var inputName : String // This is the property I want to receive and init
    
    override init (frame : CGRect) {
        super.init(frame : frame)
        // [this is where i will use the inputName property passed on initialization] 
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder) 
    }
    // [other functions and stuff working fine here]
    }
    

    我尝试了很多方法,但我对UIView初始值设定项和我通常初始化非子类类的方式感到困惑。

    如何修改此代码以接收字符串属性,并对其进行初始化?谢谢

    1 回复  |  直到 8 年前
        1
  •  2
  •   trndjc    5 年前

    如果要初始化 UIView 对于自定义属性,必须重新配置其初始值设定项:

    class InputWithIncrementView: UIView {
        let inputName: String
    
        init(inputName: String) {
            self.inputName = inputName
            super.init(frame: .zero)
        }
    
        required init?(coder aDecoder: NSCoder) {
            return nil
        }
    }