potato
potato

Reputation: 4589

Initializing a Swift array with UIImageView repeatedValue() does not seem to work

I am trying to create a 5 UIImageView programmatically, add them in a row as subviews in init(frame:) method of parent UIView. When I run the code, only the last image view shows up. First 4 are missing.

I am initializing an array of UIImageView using repeatedValue:.
Is this a proper use of the initialization method?

This is the code I am using:

import UIKit

class DistanceView: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
    print("init frame called")

    let distances = [UIImageView](count: 5, repeatedValue: UIImageView())
    distances[0].image=UIImage(named: "1")
    distances[1].image=UIImage(named: "2")
    distances[2].image=UIImage(named: "3")
    distances[3].image=UIImage(named: "4")
    distances[4].image=UIImage(named: "5")

    for var i = 0; i<5; i++ {
        distances[i].frame=CGRectMake(0+CGFloat(i)*frame.width*0.1, 0, 0.06*frame.width, 0.06*frame.width*1.6377)
        self.addSubview(distances[i])

    }
}

required init?(coder aDecoder: NSCoder) {
    print("init coder called")

    fatalError("init(coder:) has not been implemented")
}

}

Upvotes: 0

Views: 569

Answers (1)

SwiftArchitect
SwiftArchitect

Reputation: 48514

Beware of repeatedValue

The value every element in a Swift array initialized with repeatedValue() is identical.

Intermediate array

var distances = [UIImageView]()
for i in 1...5 {
    let imageView = UIImageView(image: UIImage(named: "image\(i)"))
    distances.append(imageView)
}

for i in 0 ..< distances.count {
    distances[i].frame =
        CGRectMake(0+CGFloat(i)*frame.width*0.1, 0,
        0.06*frame.width, 0.06*frame.width*1.6377)
    self.addSubview(distances[i])
}

No intermediate array

You may not need to cache your UIImageView in a separate array in the first place. You could even iterate using .subviews after the addSubview phase.

for i in 0...4 {
    let imageView = UIImageView(image: UIImage( named: "image\(1+i)"))
    imageView.frame =
        CGRectMake(0+CGFloat(i)*frame.width*0.1, 0,
        0.06*frame.width, 0.06*frame.width*1.6377)
    self.addSubview(imageView)
}

You are initializing your array with n times the same value. You are creating a single repeated UIImageView.

let distances = [UIImageView](count: 5, repeatedValue: UIImageView())

Upvotes: 2

Related Questions