Swift Changing the size of tableview cells

家住魔仙堡 提交于 2019-12-11 19:13:46

问题


just like the title says I'm searching for a way to change the size of each cell in my tableview. I have 2 questions:

1) How can I change the size of all cells by the same amount in my tableview?

2) Is it possible to automatically adjust the size of the cell based on the length of the text in that particular cell?

I'm aware that there are already similar questions asked before but I couldn't manage to implement their answers correctly as they've been outdated for some time now. I'd appreciate any help, thank you in advance!


回答1:


1) To change size of all cells with same type, first you need to create CellType, here is the explanation how to do this. https://stackoverflow.com/a/51979506/8417137 or you can check for indexPath.row, but it's not cool :)

Than here:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    switch cellType {
    case firstType:
      return firstCellTypeHeight
    case secondType: 
      return secondCellTypeHeight
    default:
      return defaultCellHeight
    }
}

2) Yes, its possible. You create your CustomCell. In your CustomCell you should setup your textFields or labels inside ContentView. Your views with text will stretch your cell.

Important thing. In method above you must return special height like that.

return UITableViewAutomaticDimension

For example your code will looks like that.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    switch cellType {
    case firstType:
      return firstCellTypeHeight
    case secondType: 
      return secondCellTypeHeight
    // Your stretching cell
    case textCellType:
      return UITableViewAutomaticDimension
    }
}

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    switch cellType {
    case firstType:
      return firstCellTypeHeight
    case secondType: 
      return secondCellTypeHeight
    // Your stretching cell
    case textCellType:
      return UITableViewAutomaticDimension
    }
}


来源:https://stackoverflow.com/questions/52019249/swift-changing-the-size-of-tableview-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!