func addStartingButtons2() {
let button = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30))
button.layer.cornerRadius = 10 // get some fancy pantsy rounding
button.backgroundColor = UIColor.darkGray
button.setTitle("Button for Villain: \(String(describing: hashes[button]))", for: UIControlState.normal)
buttons.append(button)
buttons.append(button)
for button in buttons {
self.view.addSubview(button)
button.frame.origin.y += 50
}
}
其中:
var hashes = [UIButton : [Double]]()
var buttons = [UIButton]()
想要在其他地方添加此功能2个相同的按钮,但只实现一个按钮
答案 0 :(得分:0)
这不起作用。您的数组buttons
正在存储按钮的引用,因此您实际上将两个引用放入数组中。
要自己查看结果,在循环中放置一个断点,您将看到两次具有相同地址的按钮。
如果您想拥有多个按钮,则必须逐个创建。
答案 1 :(得分:0)
嗯,是的,你试图两次添加相同的按钮。
我没有测试代码,但你应该能够通过将逻辑放在for循环中并在按钮之间添加一些填充来实现,否则你会看到它们重叠。
这样的事情:
func addStartingButtons2() {
for villain in villains { // this depends on your needs, it's just an example
let button = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30))
// Add offset for the next button.
buttonY += 40
button.layer.cornerRadius = 10 // get some fancy pantsy rounding
button.backgroundColor = UIColor.darkGray
button.setTitle("Button for Villain: \(String(describing: hashes[button]))", for: UIControlState.normal)
buttons.append(button)
}
for button in buttons {
self.view.addSubview(button)
button.frame.origin.y += 50
}
// If you want to avoid the second loop
// you can just put view.addSubview(button) inside the first for loop
}