【问题标题】:Correct way to delete item uitableview swift 4删除项目uitableview swift 4的正确方法
【发布时间】:2020-05-09 20:29:40
【问题描述】:

我有一个带有 3 个部分(3 个单元格)的 UitableView,在第 1 部分中,我有一个用户可以使用按钮删除的项目列表,所有删除过程都很好,但是当我删除一个项目时; uitableview 到顶部和底部(类似于重新加载视图),我想要那个

当用户删除一个项目时,只从位置删除这是我的代码

    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var value: Int = 0
        if(section == 0){
            value = 1
        }else if(section == 1){
            value = items.count //20
        }else if(section == 2){
            value = 1
        }
        return value
    }

    @objc func delete_item(sender: UIButton){
        let point = sender.convert(CGPoint.zero, to: tv_items)
        guard let indexPath = tv_items.indexPathForRow(at: point) else{
            return
        }
        tv_items.beginUpdates()
        self.items.remove(at: indexPath.row)
        tv_items.deleteRows(at: [indexPath], with: .fade)
        tv_items.endUpdates()
    }


    cell.btn_delete.tag = indexPath.row
    cell.btn_delete.addTarget(self, action: #selector(delete_item), for: .touchUpInside)

提前致谢

【问题讨论】:

标签: ios swift xcode swift4


【解决方案1】:

使用下面的方法,我认为它会解决你的问题:-

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
return 50.0 // height of the row (Eg. 50.0)
}

【讨论】:

    【解决方案2】:

    如果您使用的是estimatedHeightForRowAt,请禁用此功能并使用heightForRowAt 功能。

    或者,在endUpdates() 之后使用它:

    tv_items.scrollToRow(at: indexPath, at: .top, animated: false)
    

    如果你有一个恒定的行高,你可以使用:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80 // or any constant height
    }
    

    如果您需要根据内容改变高度,请让我知道内容是什么,以便我提供帮助。

    【讨论】:

    • 如何使用 heightforRowat,我是新手
    • @Israel,我已更新我的答案以显示设置恒定高度。如果您需要根据内容改变高度,请让我知道。编码愉快!
    • 我会努力做到的
    • 如果这对你有用,请接受这个答案。如果没有,请让我知道。
    猜你喜欢
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 2017-01-30
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多