This question already has answers here:
How to loop through Outlets of a UIViewController with Swift
                                
                                    (2个答案)
                                
                        
                                3年前关闭。
            
                    
我有这些店铺...

@IBOutlet weak var pill1: UIImageView!
@IBOutlet weak var pill2: UIImageView!
@IBOutlet weak var pill3: UIImageView!
@IBOutlet weak var pill4: UIImageView!
@IBOutlet weak var pill5: UIImageView!
@IBOutlet weak var pill6: UIImageView!
@IBOutlet weak var pill7: UIImageView!
@IBOutlet weak var pill8: UIImageView!
@IBOutlet weak var pill9: UIImageView!
@IBOutlet weak var pill10: UIImageView!


我需要将它们全部隐藏在“ viewDidLoad”函数中。例如...

self.pill1.isHidden = true
self.pill2.isHidden = true
self.pill3.isHidden = true
etc...
etc....all the way to...
self.pill10.isHidden = true


但是,除了编写重复行非常相似的10遍之外,我如何使用“ for循环”或任何所需的方法使它更整洁。

例如,

for index in 1...10 {

   pill(insert index here somehow).isHidden = true

}


我尝试了几种不同的方法,但是在字符串类型等方面遇到了错误。我是新手。任何帮助表示赞赏。谢谢

最佳答案

您可以将视图放入这样的数组中:

for pill in [pill1, pill2, pill3, pill4, pill5, pill6, pill7, pill8, pill9, pill10] {
    pill.isHidden = true
}




您可以考虑使用@IBOutlet集合。在这种情况下,您所有的插座都将连接到相同的collection(数组)变量:

@IBOutlet var pills: [UIImageView]!

for pill in pills {
    pill.isHidden = true
}

10-07 20:37