我是编程新手。
如下所示,我在UIView上有很多按钮。
在这种情况下,什么样的方法可以用短代码来表示?
class ViewController: UIViewController {
@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
@IBOutlet weak var buttonC: UIButton!
@IBOutlet weak var buttonD: UIButton!
@IBOutlet weak var buttonE: UIButton!
@IBOutlet weak var buttonF: UIButton!
@IBOutlet weak var buttonG: UIButton!
@IBOutlet weak var buttonH: UIButton!
@IBOutlet weak var buttonI: UIButton!
@IBOutlet weak var buttonJ: UIButton!
@IBOutlet weak var alphaView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.insertSubview(self.buttonA, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonB, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonC, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonD, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonE, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonF, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonG, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonH, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonI, aboveSubview: self.alphaView)
self.view.insertSubview(self.buttonJ, aboveSubview: self.alphaView)
}
}
最佳答案
创建一个outlet集合并将所有按钮连接到它。然后像这样迭代。
@IBOutlet var buttons: [UIButton]!{
didSet{
for button in self.buttons{
self.view.insertSubview(button, aboveSubview: self.alphaView)
}
}
}
关于swift - 请告诉我如何写短代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45579740/