简体   繁体   中英

Custom UIView subclass, required to implement init(coder:) when using instance vars

I've read several posts about why you would need to implement the constructor init(coder:) of a UIView when trying to create your own constructor (it's because UIView inherits from NSCoding protocal and by using a custom contructor it will no longer inherit the parent constructors.

My question is why this class doesn't need to implement init(coder:)

import UIKit

class CardView: UIView {

    @IBInspectable var cornerRadius : CGFloat = 3.0

    // layoutSubviews is called when view is created
    override func layoutSubviews() {
        layer.cornerRadius = cornerRadius

        layer.masksToBounds = true // Set the false to see shadows. TODO: Figure out how to clip subviews and allow a shadow

        layer.shadowOffset = CGSize(width: 0, height: 3)
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowRadius = 9.0
        layer.shadowOpacity = 0.12
    }

}

when this class does:

import UIKit

class ColorView: UIView {

    var color : UIColor

    override func layoutSubviews() {
        //layer.backgroundColor = self.color.cgColor
    }

}

I'm looking for the technical reason that the ColorView class now requires a constructor when the CardView class doesn't.

It's because ColorView does not provide any initializer or default value for color . If you change the var definition to eg var color = UIColor.black the initializer requirement goes away.

For the initialization of class in Swift, you have to make sure that at the time of initialization either you have given a default value to all the stored properties or you have declared them as optional.

By declaring as Optional means, it's default value at the time of initialization is nil.

So in the CardView there is only one stored property "cornerRadius" and you have given the default value 3.0. So no init(coder:) required.

In ColorView class, there is only one store property "color", neither you have given a value to it nor you declared it as optional. So init(coder:) is required.

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