以编程方式创建的按钮不响应目标,swift



我正在第1节的tableView标题中创建一个按钮。

我是这样做的:

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);

最新更新