我正在尝试做我认为使用Swift的简单任务。我创建了一个自定义TableView单元格,并向其中添加了一个按钮。我希望能够看到单击按钮时发生的某些动作。不幸的是,当我单击按钮时,没有任何反应。有人可以阐明这一点吗?我将代码放在下面:
自定义TableView单元格:
import UIKit
class TestTableViewCell: UITableViewCell {
@IBOutlet weak var testBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func buttonTappedOnCell()
{
println("buttonTapped!")
}
}
下面是进行调用的View Controller中的代码:
func tableView(tableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
tableView.registerNib(UINib(nibName:"TestTableViewCell", bundle:nil), forCellReuseIdentifier:"TestButtonCell")
let cell =
tableView.dequeueReusableCellWithIdentifier("TestButtonCell", forIndexPath: indexPath) as TestTableViewCell
cell.testBtn.addTarget(cell, action: "buttonTappedOnCell", forControlEvents: UIControlEvents.TouchDown)
return cell
}
我还尝试将调用更改为包括':'-> cell.testBtn.addTarget(cell,action:“ buttonTappedOnCell:”,forControlEvents:UIControlEvents.TouchDown),但这没有用。我尝试过的另一件事是将调用函数移到视图控制器中,并使目标动作指向self。不幸的是,这也不起作用。一个简短的例子可以很好地说明这一工作。归根结底,我们希望能够拥有一个包含6个单选按钮的自定义表格视图单元,允许用户仅选择一个。但是,婴儿在这一点上首先迈出了第一步。谢谢你的帮助。
我认为问题是由您在代码中指定的事件引起的。
cell.testBtn.addTarget(cell, action: "buttonTappedOnCell", forControlEvents: UIControlEvents.TouchDown)
更改ToouchDown
为TouchUpInside
cell.testBtn.addTarget(cell, action: "buttonTappedOnCell", forControlEvents: UIControlEvents.TouchUpInside)
另外,为什么要以编程方式设置它?从您的代码中,我认为您在情节提要板上有按钮。那么,为什么要以编程方式添加IBAction?(因为该动作也被调用在同一类上)。
将您声明buttonTappedOnCell
为IBAction,并将其直接连接到情节提要/ xib上的按钮。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句