【问题标题】:How can I make UITableViewCell stick to bottom when isEditing is enabled?启用 isEditing 时,如何使 UITableViewCell 粘在底部?
【发布时间】:2020-10-02 14:40:12
【问题描述】:

我在tableview 的最底部有一个UITableViewCell,它的功能是将新对象添加到列表中。但我也希望用户能够移动他的对象。我无法解决的问题来了:当tableView.isEditing 为真时,我怎样才能使UITableViewCell 不可移动,因此它始终位于部分的底部,即使用户尝试将其移动到那里?

【问题讨论】:

  • 几个选项,具体取决于您的具体需求。一种方法是让你的最后一行成为表格视图页脚而不是一行。另一个方法是为最后一行返回falsecanMoveRowAt 并“重置”moveRowAt 中的位置,如果目的地超过最后一行。

标签: ios swift xcode uitableview uikit


【解决方案1】:

这是一个防止行移过最后一行的简单示例:

class ReorderViewController: UITableViewController {
    var myData = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Don't let me move!"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let btn = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(self.startEditing(_:)))
        navigationItem.rightBarButtonItem = btn
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    @objc func startEditing(_ sender: Any) {
        isEditing = !isEditing
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = myData[indexPath.row]
        return cell
    }
    
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // don't allow last row to move
        return indexPath.row < (myData.count - 1)
    }
    override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
        // if user tries to drop past last row
        if proposedDestinationIndexPath.row == myData.count - 1 {
            // send it back to original row
            return sourceIndexPath
        }
        return proposedDestinationIndexPath
    }
    override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let itemToMove = myData[sourceIndexPath.row]
        myData.remove(at: sourceIndexPath.row)
        myData.insert(itemToMove, at: destinationIndexPath.row)
    }
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 2022-01-23
    • 2023-04-01
    • 2013-09-26
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多