ios - 在 tableview 中点击的两个 Action

标签 ios swift uitableview swift4

在 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/

相关文章:

ios - 如何在后台队列上渲染上下文?

ios - 更改AppDelegate的 Root View Controller 导致UIViewControllerHierarchyInconsistency异常

swift - 对象之间有什么区别(forKey :) and value(forKey:) in UserDefaults?

swift - 如何设置Mapkit用户跟踪按钮状态

iphone - 当选择 UITableView 中的行时,使 UINavigationBar 中的完成按钮出现

ios - 为什么 AVAssetWriter 会膨胀视频文件?

iOS - 创建约束时查看顺序

ios - 当 UITableViewController 嵌入到 UIViewController 中的容器中时,额外的表格单元格

ios - 以字符串格式获取 Web 服务响应

objective-c - 后退按钮未出现在推送的 UIViewController 上