[英]What is the action for custom accessory view button - swift
这似乎在 swift 和 objc 中被问过几次,但我看不到 swift 的正确答案,所以希望这次有人能帮助我。 我创建了一个自定义附件视图按钮,但需要正确的按钮操作:因为“accessoryButtonTapped”是一个无法识别的选择器。
调用 tableViewCellDelegate 方法 willSelectRowAtIndexPath 所需的选择器是什么?
我的代码是:
let cellAudioButton = UIButton(type: .Custom)
cellAudioButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
cellAudioButton.addTarget(self, action: "accessoryButtonTapped", forControlEvents: .TouchUpInside) //INCORRECT ACTION:
cellAudioButton.setImage(UIImage(named: "blueSpeaker.png"), forState: .Normal)
cellAudioButton.contentMode = .ScaleAspectFit
cell.accessoryView = cellAudioButton as UIView
提前感谢任何可以提供帮助的人。
为什么需要调用willSelectRowAtIndexPath
? 你已经做对了一切,为了解决你unrecognized selector
错误,只需创建一个在你点击cell.accessoryView
时调用的cell.accessoryView
。 在你的情况下:
func accessoryButtonTapped(){
print("Tapped")
}
更新
如果你想获得 indexPath 你可以
给你的cellAudioButton
添加一个标签:
cellAudioButton.tag = indexPath.row
在你的addTarget
添加一个:
来传递一个参数
在你的功能中
func accessoryButtonTapped(sender : AnyObject){
print(sender.tag)
print("Tapped")
}
所以整个代码:
let cellAudioButton = UIButton(type: .Custom)
cellAudioButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
cellAudioButton.addTarget(self, action: "accessoryButtonTapped:", forControlEvents: .TouchUpInside)
cellAudioButton.setImage(UIImage(named: "blueSpeaker.png"), forState: .Normal)
cellAudioButton.contentMode = .ScaleAspectFit
cellAudioButton.tag = indexPath.row
cell.accessoryView = cellAudioButton as UIView
func accessoryButtonTapped(sender : AnyObject){
print(sender.tag)
print("Tapped")
}
Swift 3.1更新Rashwan解决方案
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
//add button as accessory view
let cellAudioButton = UIButton(type: .custom)
cellAudioButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
cellAudioButton.addTarget(self, action: #selector(ViewController.accessoryButtonTapped(sender:)), for: .touchUpInside)
cellAudioButton.setImage(UIImage(named: "closeRed"), for: .normal)
cellAudioButton.contentMode = .scaleAspectFit
cellAudioButton.tag = indexPath.row
cell.accessoryView = cellAudioButton as UIView
return cell
}
func accessoryButtonTapped(sender : UIButton){
print(sender.tag)
print("Tapped")
}
笔记:
这里ViewController是类的名称,如LoginViewController
为什么不使用UITableViewDelegate
?
@available(iOS 2.0, *)
optional func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath)
为了澄清这一点,但这是可能的。 您可以将自定义 UI 元素用作附件按钮。
这是一个示例——假设您使用的是 Interface Builder。 将UISwitch
添加到自定义单元格。 现在右键单击从UITableViewCell
拖放至UISwitch
。 选择accessoryView
作为出口连接。 完毕。
每次按下开关按钮时,都会触发委托方法。 这也应该适用于其他操作元素,例如UIButton
s。 这正是 OP 要求的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.