2016-12-12 228 views
0

我有一个有趣的问题。因为我是Swift新手。在自定义单元格内添加自定义单元格

我已在TableView上创建并使用Storyboard添加了CUSTOM CELL。现在我想添加一个自定义单元格当第一自定义单元格 UIButton的点击。

第二个自定义电池是使用XIB创建。现在当我注册第二个单元格didload然后我看到空白tableview作为第二个自定义单元格是空白。

我已经使用以下代码:

在索引登记第二小区

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对象为故事板细胞和Customcell为XIB第二个定制单元。

请建议我该怎么做。

回答

1

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

下一个出口,你需要注册在viewDidLoad方法自定义单元格:

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

如果要在按下时想要修改多个单元格,最简单的方法是保存已选择的单元格阵列。这可以是视图控制器内的变量:

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的平滑动画。