如何在Swift中迭代对象/变量。我有附加对象时可以创建数组或字典,这样我就不必为每个按钮编写代码。我是个nubie所以请跟我说话,就像我四岁。感谢您的帮助。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
...
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.button1.alpha = 0.0
self.button2.alpha = 0.0
self.button3.alpha = 0.0
...
}
答案 0 :(得分:3)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
var arrayOfButtons = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
arrayOfButtons = [button1, button2, button3]
for button in arrayOfButtons {
button.alpha = 0.0
}
}
答案 1 :(得分:1)
除了Tim的回答,您还可以通过编程方式创建按钮,并在代码中处理它们!
override func viewDidLoad() {
for i in 1...10 {
let button = UIButton()
button.frame = CGRectMake((CGFloat(i-1)*50), 0, 50, 50)
button.targetForAction("buttonClick:", withSender: self)
button.tag = i
self.view.addSubview(button)
}
}
func buttonClick(sender:AnyObject) {
let tag = sender.tag!
//click logic here
}