【发布时间】:2018-02-23 10:39:08
【问题描述】:
我在http://helpmecodeswift.com/advanced-functions/generating-uibuttons-loop找到了UIButtons 的动态视图示例
我将此代码插入到我的应用程序中,但遗憾的是我找不到为每个按钮设置标签的方法。
我的目标是知道点击了哪个按钮,计算每个按钮的点击量并将此信息保存到我的数据库中。
override func viewDidLoad() {
super.viewDidLoad()
var arrayOfVillains = ["santa", "bugs", "superman", "batman"]
var buttonY: CGFloat = 20
for villain in arrayOfVillains {
let villainButton = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30))
buttonY = buttonY + 50 // we are going to space these UIButtons 50px apart
villainButton.layer.cornerRadius = 10 // get some fancy pantsy rounding
villainButton.backgroundColor = UIColor.darkGrayColor()
villainButton.setTitle("Button for Villain: \(villain)", forState: UIControlState.Normal) // We are going to use the item name as the Button Title here.
villainButton.titleLabel?.text = "\(villain)"
villainButton.addTarget(self, action: "villainButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(villainButton) // myView in this case is the view you want these buttons added
}
}
func villainButtonPressed(sender:UIButton!) {
if sender.titleLabel?.text != nil {
println("You have chosen Villain: \(sender.titleLabel?.text)")
} else {
println("Nowhere to go :/")
}
}
}
那么如何在代码中为/从每个按钮设置和获取标签(在这个例子中)? 提前谢谢!
【问题讨论】: