简体   繁体   English

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

[英]How to properly init passed property in subclass of UIView?

I have a subclass of UIView that I would like to pass a property to.我有一个 UIView 的子类,我想将一个属性传递给它。 As much as I've tried, I don't truly understand all elements of initializing.尽我所能,我并没有真正理解初始化的所有元素。

Here is a simplified version of my code:这是我的代码的简化版本:

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]
}

I have tried a number of things, but I'm getting confused between the UIView initializer and the way I normally initialize a non-subclassed class.我已经尝试了很多东西,但是我在 UIView 初始化程序和我通常初始化非子类类的方式之间感到困惑。

How do I modify this code to receive the string property, initialize it?如何修改此代码以接收字符串属性并对其进行初始化? Thanks谢谢

If you want to initialize a UIView with a custom property you must reconfigure its initializer:如果要使用自定义属性初始化UIView ,则必须重新配置其初始化程序:

class InputWithIncrementView: UIView {
    let inputName: String

    init(inputName: String) {
        self.inputName = inputName
        super.init(frame: .zero)
    }

    required init?(coder aDecoder: NSCoder) {
        return nil
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM