Pass variable to custom UITableViewCell from UIViewController

前端 未结 4 739
死守一世寂寞
死守一世寂寞 2021-01-20 20:59

Here is how I use my custom UITableViewCell RunningTableViewCell inside UIViewController:

func tableView(tableView: UITableView, ce         


        
4条回答
  •  被撕碎了的回忆
    2021-01-20 21:29

    awakeFromNib is called right after the view and its subviews were allocated and initialized.

    So your code from awakeFromNib in RunningTableViewCell for each cell is called before delegate method func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell. That is why isTop and isBottom are nil in awakeFromNib.

    You can define method in RunningTableViewCell, which will load cell with this variables.

    func load(isTop: Bool, isBottom: Bool) {
        self.isTop = isTop
        self.isBottom = isBottom
    
        // Update cell UI as you wish
    }
    

    And finally rewrite delegate method func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell in your view controller.

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! RunningTableViewCell
    
        let isTop = indexPath.row == 0
        let isBottom = indexPath.row == myArray.count-1
    
        cell.load(isTop, isBottom: isBottom)
    
        return cell
    }
    

提交回复
热议问题