自定义UITableViewCell上的UIButton无法工作(Swift)

3

非常抱歉我的英语不好,如果我说错了什么,请见谅。这是我在这里提出的第一个问题。

我有一个自定义的UITableViewCell作为*.xib文件中的视图,其中包含了一个UIImage和一个在该UIImage上的按钮。 我将此按钮与我的CustomTableViewCell.swift类中的outlet连接了起来。

@IBOutlet weak var authorImage: UIImageView!
@IBOutlet weak var authorButton: UIButton!

在MyTableViewController.swift中,我已经注册了一个nib。
tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "my_cell")

我编写了一个类似这样的 cellForRow... 函数:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("my_cell", forIndexPath: indexPath) as! CustomTableViewCell
    cell.authorButton.addTarget(self, action: "authorButtonPressed:", forControlEvents: .TouchUpInside)
    return cell
}

最后,我有这个函数(我在addTarget中使用):

func authorButtonPressed (sender:UIButton!) {
    print("Hi!")//line1
    print(sender)
}

在第一行设置断点,但这个函数从未被调用。

当我点击按钮时,我也意识到它没有动画效果。

我该如何修复它或找到解决方案?

提前感谢您。


你确定按钮在图片上方而不是在其后面吗?如果你暂时移除/隐藏图片,问题是否仍然存在? - j.f.
@j.f. 我刚刚删除了按钮周围的所有内容。但是当我点击它时,它仍然没有变化。authorButtonPressed:函数也没有开始执行。我还尝试使用视图层次结构调试器查看是否有东西覆盖我的按钮,但唯一覆盖按钮的是UITableViewCellContentView。这是图片链接:https://www.dropbox.com/s/qb08tm08l5i0i9a/%D0%A1%D0%BD%D0%B8%D0%BC%D0%BE%D0%BA%20%D1%8D%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%202015-10-26%20%D0%B2%2023.55.09.png?dl=0 - Nikolay Pryahin
你能否发布一下你的xib截图(包括文档大纲)? - joern
@joern 我已经将单元格上的所有内容都删除了,只剩下我的按钮 https://www.dropbox.com/s/be8p26d7hbqy1qs/%D0%A1%D0%BD%D0%B8%D0%BC%D0%BE%D0%BA%20%D1%8D%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%202015-10-27%20%D0%B2%200.21.14.png?dl=0 - Nikolay Pryahin
4个回答

4
您在nib中使用了一个UIView作为根视图。对于自定义的UITableViewCell,您需要将根视图设置为UITableViewCell:

enter image description here

因此,您需要创建一个空的xib文件,然后将UITableViewCell拖到其中。然后开始向ContentView添加子视图。


0

你不应该在这个函数中添加 add target:

override func tableView(tableView: UITableView, cellForRowAtIndexPath    indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("my_cell", forIndexPath: indexPath) as! CustomTableViewCell
**cell.authorButton.addTarget(self, action: "authorButtonPressed:", forControlEvents: .TouchUpInside)**
return cell
}

你只需要在你的单元格中添加插座操作即可。就像这段代码:

@IBAction func testPressed(sender: AnyObject) {
    print("test")
}

0

按照Joern的解决方案,然后通过单击选择表视图单元格,并确保属性检查器窗格中用户交互已启用属性的复选标记已启用。


0

你使用过这个神奇的按钮吗? 在此输入图像描述

多亏了它,你可以看到你的图层树,它可能包含一些奇怪的东西...就像这样。 在此输入图像描述

其他视图正在那里搞砸。只需要调查一下,伙计!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接