Swift4。自定义视图未在自定义初始化

时间:2017-09-29 17:09:39

标签: swift uiview

任何人都可以指出以下代码的问题是什么。?

 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")


}

我试图根据模数运算符显示3种不同颜色的视图。但是出于某种原因,只显示最后一个带有橙色的颜色。前两个没有出现。代码也不会崩溃。 我是否需要将自定义逻辑移动到所需的init。

感谢。

1 个答案:

答案 0 :(得分:0)

请检查如下:

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