简体   繁体   中英

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!

Given an array of UIView

let hideViews: [UIView] = ...

You can hide each view

hideViews.forEach { $0.isHidden = true }

move each view 30 points to the left

hideViews.forEach { $0.frame.origin.x -= 30 }

or both

hideViews.forEach {
    $0.isHidden = true
    $0.frame.origin.x -= 30
}

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

You don't need to force cast to Any or AnyObject. This work For Swift3:

let v = UIView()
let i = UIImageView()
let l = UILabel()
let b = UIButton()

// Swift auto infers array type, this is equal to write
// let views: [UIView] = [v, i, l, b]
let views = [v, i, l, b]


views.forEach {
    $0.isHidden = true
}

//or

for view in views {
    view.frame = CGRect.zero
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM