简体   繁体   English

Swift 3-在视图数组上设置属性

[英]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: 以前,我可以通过将多个视图(UIImageViews,UILabel和UIButtons)添加到数组中,然后遍历该数组以进行属性更改来清理代码:

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

which then became in another version of Swift: 然后成为另一个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!' 无法分配给'Bool!'类型的不可变表达式

Cannot assign to immutable expression of type 'CGRect!' 无法分配给'CGRect!'类型的不可变表达式。

Does anybody know what I'm missing here, in order to do this in Swift 3? 为了在Swift 3中做到这一点,有人知道我在这里缺少什么吗?

Thanks! 谢谢!

Given an array of UIView 给定一个UIView数组

let hideViews: [UIView] = ...

You can hide each view 您可以隐藏每个视图

hideViews.forEach { $0.isHidden = true }

move each view 30 points to the left 每个视图向左移动 30点

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. isHiddenframeUIView类的属性,因此,如果要更新属于它们的属性, AnyObject应将其AnyObjectAnyObject 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. 您无需强制转换为Any或AnyObject。 This work For Swift3: 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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