Swift addSubview () for views created with init (repeating: count) not working

Here is a ViewController that creates 4 subplots using init (repeat: count).

In viewDidLoad, I add them as subviews and set their frames. When I run the app, only the last view is added.

class ViewController: UIViewController {

    let subviews = [UIView].init(repeating: UIView(), count: 4)

    override func viewDidLoad() {
        super.viewDidLoad()
        for i in 0..<subviews.count {
            self.view.addSubview(subviews[i])
            self.subviews[i].backgroundColor = UIColor.red
            self.subviews[i].frame = CGRect(x: CGFloat(i) * 35, y: 30, width: 30, height: 30)
        }
    }

}

      

init (repeating: count) only adds the last view

Here's the same code, apart from using init (repeating: count), I'm using closure. This works great - all sub-items are added.

class ViewController: UIViewController {

    let subviews: [UIView] = {
        var subviews = [UIView]()
        for i in 0..<4 {
            subviews.append(UIView())
        }
        return subviews
    }()

    override func viewDidLoad() {
      //same as above...
    }
}

      

close initialization OK

+3


source to share


1 answer


You are adding the same instance UIView

to your array four times. Yours viewDidLoad

simply ends up moving this single kind. You need to create four separate instances UIView

.



let subviews = (0 ..< 4).map({ _ in UIView() })

      

+3


source







All Articles