【问题标题】:Add Custom Cell inside Custom Cell在自定义单元格中添加自定义单元格
【发布时间】:2016-12-12 13:02:56
【问题描述】:

我有一个有趣的问题。因为我是 Swift 新手。

我在 TableView 上创建并使用 Storyboard 添加了CUSTOM CELL。现在我想添加另一个 CUSTOM CELL 当点击第一个 CUSTOM CELL UIButton。

第二个自定义单元是使用 XIB 创建的。现在,当我在 didload 中注册第二个单元格时,我看到空白表格视图,因为第二个自定义单元格为空白。

我使用了以下代码:

用于注册第二个单元格

   self.tableView.registerNib(UINib(nibName: "customCell", bundle: nil), forCellReuseIdentifier: "customCell")

索引行的单元格

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! Cell

        cell.nameLbl.text = "Hello hello Hello"

        let Customcell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! customCell


        if self.Selected == "YES" {
            if self.selectedValue == indexPath.row {


                return Customcell
            }

            return cell

        }
        else{

            return cell
        }
    }

这里的 Cell 对象用于 Storyboard Cell,Customcell 用于 XIB Second custom cell。

请建议我如何做到这一点。

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    首先确保你的ViewController是tableView的UITableViewDelegate和UITableViewDataSource,并且你有tableView的outlet

    接下来需要在viewDidLoad方法中注册自定义单元格:

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "customCell")
    }
    

    如果您想要在按下时修改多个单元格,则最简单的方法是保存已选择的单元格数组。这可以是 ViewController 中的变量:

    var customCellIndexPaths: [IndexPath] = []
    

    当一个单元格被选中时,您可以简单地将其添加到自定义单元格 IndexPaths 数组中(如果它还不是自定义单元格),然后重新加载该单元格:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if customCellIndexPaths.contains(indexPath) == false {
            customCellIndexPaths.append(indexPath)
            tableView.reloadRows(at: [indexPath], with: .automatic)
        }
    }
    

    在 cellForRowAt 方法中,我们必须检查单元格是否被选中,如果是则返回自定义单元格,否则返回正常单元格:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        if customCellIndexPaths.contains(indexPath) {
            return tableView.dequeueReusableCell(withIdentifier: "customCell")!
        }
    
        let cell = UITableViewCell(style: .default, reuseIdentifier: "normalCell")
        cell.textLabel?.text = "Regular Cell"
        return cell
    }
    

    你有它。现在您应该会收到一个正常单元格在被选中时变为 CustomCell 的平滑动画。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 2023-01-16
      • 2012-07-10
      相关资源
      最近更新 更多