RanLearns RanLearns - 2 months ago 18
iOS Question

Swift 3 - setting a property on an array of views

I was previously able to clean up my code by adding multiple views (UIImageViews, UILabels, and UIButtons) to an array and then iterating through the array to make a property change like this:

var hideViews = [imageView1, imageView2, label1, button1, button2]
for eachView in hideViews {
eachView.isHidden = true
}


which then became in another version of Swift:

var hideViews = [imageView1, imageView2, label1, button1, button2] as [Any]
for eachView in hideViews {
(eachView as AnyObject).isHidden = true
}


I was also able to use this to move several views at once:

for view in viewsToMove {
(view as AnyObject).frame = CGRect(x: view.frame.origin.x - 30, y: view.frame.origin.y, width: view.frame.width, height: view.frame.height)
}


I am now getting the errors:

Cannot assign to immutable expression of type 'Bool!'

Cannot assign to immutable expression of type 'CGRect!'

Does anybody know what I'm missing here, in order to do this in Swift 3?

Thanks!

Answer

isHidden and frame are properties of UIView class so you should not cast them to AnyObject if you want to update properties that belong to them. Just do:

let views: [UIView] = [imageView1, imageView2, label1, button1, button2]

for view in views {
  view.isHidden = true
  view.frame = CGRect(x: ..., y: ...)
}