您好,我想弄清楚如何在 Storyboard 中的 UItable 中的自定义单元格内调用 UIButton。目前我有一个库可以创建一个工作正常的侧边菜单(更多信息在这里),我可以看到我在启动模拟器时放置的按钮。但是,当我点击按钮时,操作未被触发,您能指导我如何实现吗?
重要的是要注意该表完全是在 Storyboard 中创建的。
我在 TopratedVC.swift
中进行的代码获取触发操作的按钮:
override func viewDidLoad() {
super.viewDidLoad()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewVibrantCell") as! CellClassMenu
cell.sendFeedBackBtn.tag = indexPath.row
cell.sendFeedBackBtn.addTarget(self, action: "sendFeedBackBtnAction:", forControlEvents: .TouchUpInside)
cell.contentView.userInteractionEnabled = false //tried with true as well, no difference
cell.bringSubviewToFront(cell.sendFeedBackBtn)
cell.userInteractionEnabled = true
return cell
}
func sendFeedBackBtnAction(sender: UIButton){
print("sendFeedBackBtnAction tapped")
}
我的 UITableViewVibrantCell.swift
文件包含以下内容:
import UIKit
class UITableViewVibrantCell: UITableViewCell {
@IBOutlet var sendFeedBackBtn: UIButton!
}
我的 sndFeedBackBtn
有一个指向 UITableViewVibrantCellsendFeedBackBtn
的引用导出,它有一个类 UITableViewVibrantCell
。我究竟做错了什么?谢谢。
最佳答案
在您的帖子中,您显示了一个 UITableViewVibrantCell
类,并使具有“UITableViewVibrantCell”标识符的单元格出队,但将其转换为 CellClassMenu
?
无论如何,更好的做法是为操作创建一个单元委托(delegate),并让您的 Controller 决定实现,而不是每次单元出队时都添加一个目标。你可以这样做:
UITableViewVibrantCell
import UIKit
protocol UITableViewVibrantCellDelegate: NSObjectProtocol {
func buttonPressed(sender: UIButton)
}
class UITableViewVibrantCell: UITableViewCell {
var delegate: UITableViewVibrantCellDelegate?
@IBOutlet var feedbackButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
feedBackButton.addTarget(self, action: #selector(self.buttonPressed(_:)), forControlEvents: .TouchUpInside)
}
func buttonPressed(sender: UIButton) {
delegate?.buttonPressed(sender)
}
}
顶级风投
class TopratedVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewVibrantCell") as! UITableViewVibrantCell
cell.delegate = self
return cell
}
// MARK: - UITableViewVibrantCellDelegate
func buttonPressed(sender: UIButton) {
print("feedbackButton tapped")
}
}
关于ios - 表内的 UIButton 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39234636/