简体   繁体   中英

How to init custom UIView in Swift 1.2

I wish to init a UIView subclass programmatically, which should be initiated with, say, an Int. I'm looking to do something like this:

class OneFingerView: UIView
{
    let id: Int

    init(id: Int)
    {
        self.id = id
        super.init()
    }

    required init(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }
}

But get an error

Must call a designated initializer of superclass UIView

My attempt before this was as follows:

class OneFingerView: UIView
{
    let id: Int
    var delegate: OneFingerViewProtocol? = nil

    init(id: Int, frame: CGRect)
    {
        self.id = id
        super.init(frame: frame)
    }

    override init(frame: CGRect)
    {
        super.init(frame: frame)
    }
}

But then I get an error that I have not implemented init(coder:).

How do I do this? There seems to be an endless cycle of various errors no matter which approach I take.

Override initWithFrame and call super.init(frame:)

I misspoke in my comment. You also need to implement init(coder:) In that method you won't be able to provide your id parameter, and will need to set it somewhere else. You might look at making your id property IBInspectable and setting it in IB.

The init(coder:) method is designed to save any properties you want for your custom subclass. What you do is to override both init(coder:) and encodeWithCoder() . In those methods you'd call the super version, and then load/save your extra property in your custom code (using the methods in NSKeyedUnarchiver and NSKeyedArchiver .)

However, init(coder:) and encode(coder:) aren't very useful for objects you create in IB, because IB doesn't set up your custom properties for you. Better to just use the vanilla init(coder:) that simply calls super, and configure your objects in code, or with IBDesignable properties, as mentioned above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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