繁体   English   中英

从右向左“滑动” UITableViewCell

[英]UITableViewCell “full” swipe, right-to-left

我有一个UITableView,当从右向左滑动时,单元格已经实现了两个自定义按钮(UITableViewRowAction编辑动作)。 一切正常。

我想在用户“一路”(也从右到左)滑动时触发按钮的操作之一,类似于Mail.app。

代码是Swift 3,适用于iOS 9和10。

我有足够的代码。

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return .delete
 }

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    print("commit editingStyle")
}

commit editingStyle函数从不触发,正如我期望的那样。

我删除了editActionsForRowAt方法,以为我在定义自定义按钮时可能editActionsForRowAt了。 现在,我看到默认的“删除”按钮,但是仍然不会触发commit editingStyle

值得的是,这是UIViewController(不是UITableViewController)内的UITableView,其中.dataSource和.delegate都设置为相关类。 它也是NSFetchedResultsControllerDelegate。

UISwipeGestureRecognizer附加到表本身,而不是单个单元格。 当检测到滑动时,计算要滑动哪个单元格,并相应地调用滑动动作。

添加:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

我想出了一种机制来做到这一点,我认为这并不是太多的骇客-当然比我发现的其他解决方案要少。 欢迎发表评论。

我的意图是始终使用尽可能多的标准功能。 我正在做的是跟踪用户向左滑动单元主体的距离。 当达到某个阈值时,我告诉UITableView对有问题的按钮执行从editActionsForRowAt调用的相同操作。

我正在使用-225作为单元格向左移动的阈值。 这可能不适用于所有实现(并且我可能会通过更多测试来修改自己)。 在我的情况下,我有两个自定义操作,其中一个的按钮有些偏大。

我唯一真正添加的是NSTimer,我使用.UITrackingRunLoopMode将其添加到主运行循环中。 这具有在用户(且仅在)手指移动时运行的好处。 当计时器触发时,我检查一下该单元相对于主机tableView的位置。 没有添加视图,没有添加手势识别器。

在自定义UITableViewCell中,我添加了以下内容:

var trackTimer:Timer? = nil
weak var tableView:StudentsLessonsViewController? = nil

override func awakeFromNib() {
    super.awakeFromNib()
    setupTimer()
}

override func prepareForReuse() {
    super.prepareForReuse()
    setupTimer()
}

func setupTimer() {
    self.trackTimer = Timer.init(timeInterval: 0.1, target: self, selector: #selector(performActionIfScrolledFarEnough), userInfo: nil, repeats: true)
    if let trackTimer = self.trackTimer {
        RunLoop.main.add(trackTimer, forMode: .UITrackingRunLoopMode)
    }
}

func performActionIfScrolledFarEnough() {
    let globalPoint = self.superview?.convert(self.frame.origin, to: self.tableView?.tableView)
    //print("globalPoint.x: \(String(describing: globalPoint?.x))")
    if let globalPoint = globalPoint {
        if globalPoint.x < CGFloat(-225) {
            //print ("Perform Action NOW!!!")
            trackTimer?.invalidate()
            if let tableView = self.tableView {
                tableView.primaryActionButtonPressed(cell: self)
            }
        }
    }
}

在UITableView的cellForRowAtIndexPath中,我添加了:

cell?.tableView = self

我的UITableView中已经具有此功能,当用户点击editActionsForRowAt中定义的按钮之一时,我正在调用它:

func tableView.primaryActionButtonPressed(cell:UITableViewCell)

在我的primaryActionButtonPressed函数中,我从tableView中删除了单元格(概念上就像删除一样)。 不同的操作可能需要不同的实现细节。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM