【问题标题】:Swift: UITableView - swipte to delete - How to have cell content not moving while swipingSwift:UITableView - 滑动删除 - 如何让单元格内容在滑动时不移动
【发布时间】:2018-03-15 07:43:42
【问题描述】:

我已经在 UITableView 上实现了滑动删除,它可以在默认行为下正常工作,即单元格的内容在像在图像上一样滑动时向左移动。我想要实现(自定义)的是在滑动时让这个删除按钮出现在单元格内容上,即单元格中的文本不会移动。

我正在使用这种方法

 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

        let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in

            self.deletionDidStart(of: self.element(for: indexPath)!, at: indexPath)

            // use helper function to delete element at given index path
            let deleted = self.deleteElement(for: indexPath)

            // refresh tableView
            self.tableView.beginUpdates()
            self.tableView.deleteRows(at: [indexPath], with: .automatic)
            if let deletedSection = deleted.section {
                self.tableView.deleteSections(IndexSet(integer: indexPath.section), with: .automatic)
                self.deletedSection(deletedSection, at: indexPath)
            }
            self.tableView.endUpdates()

            // call deletion event handler
            self.deletedElement(deleted.element!, at: indexPath)
        }

        return [delete]
    }

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    您应该覆盖 UITableViewCellsetEditing 方法,

    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)
    
        let leadingSpace = 15
        let editingOffset = 80
    
        if editing == true {
            self.labelLeadingConstraint.constant = CGFloat(leadingSpace + editingOffset)
        } else {
            self.labelLeadingConstraint.constant = CGFloat(leadingSpace);
        }
    
        UIView.animate(withDuration: 0.1) {
            self.layoutIfNeeded()
        }
    }
    

    您需要采用IBOutletUILabel's 领先约束并以这种方式进行。

    这只是建议,实际代码可能会根据您的单元格布局进行更改。

    更新

    也可以使用下面的函数。

    func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath)
        cell?.setEditing(true, animated: true)
    }
    
    func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
        if let indexPath = indexPath {
            let cell = tableView.cellForRow(at: indexPath)
            cell?.setEditing(false, animated: true)
        }
    }
    

    希望对你有所帮助。

    【讨论】:

    • 似乎几乎像我预期的那样工作。一个小问题是不稳定这个方法似乎并不总是被调用,有时单元格内容不会回到它的位置。知道如何强制每次重新计算
    • @MichałZiobro 有时单元格内容不会返回到它的位置,是这样吗?它的输出是什么?
    • 是的,如果我解决了这个问题,我会投赞成票。我会尝试导致有时标签在结束编辑模式后留在单元格中间,或者在开始编辑模式时不移动
    • @MichałZiobro 更新 UIView.animate 函数,持续时间为 0.5
    • @MichałZiobro 它在这里工作,你能验证你的代码吗?
    猜你喜欢
    • 2016-02-19
    • 2014-11-18
    • 1970-01-01
    • 2014-04-21
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多