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

后端 未结 4 481
故里飘歌
故里飘歌 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 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.

提交回复
热议问题