以编程方式创建的按钮不响应目标,swift
button created programmatically doesn't respond to target, swift
我正在第 1 部分的 tableView header 中创建一个按钮。
我是这样做的:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
header.backgroundColor = UIColor.greenColor()
if section == 1 {
var button = UIButton()
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
header.addSubview(button)
}
return header
}
func Action(sender: UIButton){
println("button was pressed")
}
该按钮仅出现在第 1 部分(应该如此),但如果我按下它而不是打印消息,则什么也不会发生。
我的问题是我没有正确指定 button.frame。由于按钮在框架外,因此从未被调用。
button.frame = CGRectMake(5, 2, tableView.frame.size.width - 5, 18);
我正在第 1 部分的 tableView header 中创建一个按钮。
我是这样做的:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
header.backgroundColor = UIColor.greenColor()
if section == 1 {
var button = UIButton()
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
header.addSubview(button)
}
return header
}
func Action(sender: UIButton){
println("button was pressed")
}
该按钮仅出现在第 1 部分(应该如此),但如果我按下它而不是打印消息,则什么也不会发生。
我的问题是我没有正确指定 button.frame。由于按钮在框架外,因此从未被调用。
button.frame = CGRectMake(5, 2, tableView.frame.size.width - 5, 18);