【问题标题】:How to change editing style for specific cell in tableview如何更改表格视图中特定单元格的编辑样式
【发布时间】:2021-10-17 18:49:30
【问题描述】:

我有一个表格视图,其中所有单元格的编辑样式都是 .delete。但我想要一些没有编辑样式的特定单元格(这样你就不能滑动它们,.none)。有人对如何实现这个有任何建议吗?

我尝试为该特定行编写类似 UITableViewCell.EditingStyle.none 的内容,但没有成功。

在此先感谢本图斯

【问题讨论】:

  • 最好使用您尝试过的一些代码来编辑您的问题,以便我们提前为您提供帮助。

标签: swift xcode uitableview


【解决方案1】:

考虑以下示例:

class ViewController: UITableViewController {

    private let arr = (1...10).map { "Item \($0)" }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        
        cell?.textLabel?.text = arr[indexPath.row]

        return cell ?? UITableViewCell()
    }
    
    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        if indexPath.row == 2 {//<- Your condition
            return .none
        } else {
            return .delete
        }
    }
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
}

所以关键是使用editingStyleForRowAt 来更改特定单元格(甚至多个单元格)的样式(请参阅文档以获取更多参考:https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614869-tableview)。

【讨论】:

  • 非常感谢!这工作得很好:D
猜你喜欢
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多