iOS: What is a difference between dequeueReusableCell(withIdentifier:for:) and dequeueReusableCell(withIdentifier:)?

后端 未结 4 452
故里飘歌
故里飘歌 2021-01-13 18:23

According to the official documentation, there are two ways to get a reusable cell from a queue of a tableView. One is dequeueReusableCell(withIdentifier:for:)

相关标签:
4条回答
  • 2021-01-13 18:43

    Method dequeueReusableCell(withIdentifier:) is older than dequeueReusableCell(withIdentifier:for:), and the main difference between them is that first will return nil, if cell don't registered, the second will throw an exception, and an app will crash. IndexPath requires for height calculation(if defined tableView:heightForRowAtIndexPath)

    0 讨论(0)
  • 2021-01-13 18:45

    After having a look at the official documentation

 I realised that your interpretation is somewhat correct.

    Could you please have a look at this answer, as this might bring up more clarity.


    0 讨论(0)
  • 2021-01-13 18:53

    dequeueReusableCell(withIdentifier:) AND dequeueReusableCell(withIdentifier:for:)

    Both returning the cell, but older method return nil while latest method crashes the app.

    older may support upto iOS 5 while newer method support iOS 6 and Above

    0 讨论(0)
  • 2021-01-13 19:02

    If you will use below method you always get the initialized instance and it will always be the right size for that indexpath, so you will be able to do layout inside your contentview knowing that the size is correct. As this will set the cell size before returning it that's why we need to add indexPath.

    let cell: UITableViewCell = self.tableView.dequeueReusableCell(with:
      "Cell", for: indexPath)
    

    In below case you have to check if the cell is nil, configure it yourself.

        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell")
    
        if (cell == nil) {
    
          cell = UITableViewCell(style:UITableViewCellStyle.subtitle, reuseIdentifier:"Cell")
       }
    

    Note: In newer version i.e. self.tableView.dequeueReusableCell(with: "Cell", for: indexPath) app crashes if you didn't register a class/nib for the identifier. In older version i.e. tableView.dequeueReusableCell(withIdentifier: "Cell") version returns nil in that case. Moreover if you are using storyboard you don't need to worry about registering the cell.

    dequeueReusableCellWithIdentifier:forIndexPath: will always return a cell. On the other hand dequeueReusableCellWithIdentifier: will return nil if no reusable cell that's why nil check is required.

    0 讨论(0)
提交回复
热议问题