auto adjust custom UITableViewCell and Label in it to the text

前端 未结 2 977
时光说笑
时光说笑 2020-12-20 04:58

I have a custom UITableViewCell that only has one Label in it. I also set number of lines in Interface Builder to 0 as I read on StackOverflow.

         


        
相关标签:
2条回答
  • 2020-12-20 05:21

    You need to use self sizing cells.

    tableView.estimatedRowHeight = 100
     tableView.rowHeight =    UITableViewAutomaticDimension
    

    In your storyboard or xib you have to make sure that you set proper constraints in your cells. Do not set a predefined height constraint in your label. Just make sure you give top and bottom constraints. If you are not sure about the text , you can also give a minimum height constraint to the label.

    0 讨论(0)
  • 2020-12-20 05:35

    Try this code:

    Note: Both method should work.Tested in Swift 3.

    Method 1:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    tableView.estimatedRowHeight = 44.0 // standard tableViewCell height
    tableView.rowHeight = UITableViewAutomaticDimension
    
    return yourArrayName.count
    }
    

    Method 2:

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
    }
    
    override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
    }
    

    Note: You need to put this code inside your cellForRowAt

     yourCellName.sizeToFit()
     cell.textLabel?.numberOfLines = 0
    

    Output:

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题