在 tableview 中点击的两个 Action !
我有一个关于在 tableview 中点击的问题。我可以在点击时设置辅助操作吗? 1. 点击(默认)。 2. 我点击并按住选定的单元格 2-3 秒,然后执行另一个操作。
最佳答案
可以,您需要在 cell.contentView
中添加一个 UILongPressGestureRecognizer
并处理该事件,您的第一个事件“Normal Tap event”将由 触发>didSelectRowAtIndexPath
默认方法,而 hold 事件将由 UILongPressGestureRecognizer
单元实现示例
import UIKit
class LongPressTableViewCell: UITableViewCell {
var longPressGesture : UILongPressGestureRecognizer?
var longPressClosure : (()->Void)?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setupWithClosure(closure:@escaping (()->Void)) {
self.longPressClosure = closure
if(longPressGesture == nil) {
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gesture:)))
longPressGesture!.minimumPressDuration = 2
self.contentView.addGestureRecognizer(longPressGesture!)
}
}
@objc func longPressAction(gesture:UILongPressGestureRecognizer) {
if (gesture.state == UIGestureRecognizerState.began){
self.longPressClosure?()
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
TableView DataSource && Delegate 示例实现
extension ViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "LongPressTableViewCell", for: indexPath) as? LongPressTableViewCell{
cell.setupWithClosure {
//LongPress action
debugPrint("LongPress")
}
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
debugPrint("Tap Action")
}
}
关于ios - 在 tableview 中点击的两个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49486202/