user2511882 user2511882 - 3 years ago 256
Swift Question

Swift4. Custom view not being displayed in custom init

Can anyone point out what is the issue with the following piece of code.?

class CustomView: UIView {
init(_ i:Int, _ view:UIView){

super.init(frame: CGRect.init(x: 0, y: i*300, width:Int(view.frame.size.width) , height: 300))
for i in stride(from: 0, to: 3, by: 1){
var view = UIView.init(frame: CGRect.init(x: (Int(self.frame.size.width/2-50)), y: i*00, width: 100, height: 100))

switch(i%3){
case 0:
view.backgroundColor = UIColor.red
break;
case 1:
view.backgroundColor = UIColor.green
break;
case 2:
view.backgroundColor = UIColor.orange
break;
default:
break;

}

self.addSubview(view)


}

}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("not required to implement requiredInit here")


}


I am trying to display 3 different colored views based on the modulus operator. For some reason however only the last one with orange color is being displayed. The first two do not show up. The code doesn't crash either.
Do i need to move the custom logic into the required init.

Thanks.

Answer Source

Please check like below :

init(_ i:Int, _ view:UIView){
    super.init(frame: CGRect.init(x: 0, y: i*300, width:Int(view.frame.size.width) , height: 300))
    for i in stride(from: 0, to: 3, by: 1){
        var subview = UIView.init(frame: CGRect.init(x: (Int(self.frame.size.width/2-50)), y: i*100, width: 100, height: 100))

        switch(i%3){
        case 0:
            subview.backgroundColor = UIColor.red
            break;
        case 1:
            subview.backgroundColor = UIColor.green
            break;
        case 2:
            subview.backgroundColor = UIColor.orange
            break;
        default:
            break;
        }
        view.addSubview(subview)
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download