Aligning multiple runtime generated UILabels in a UITableView

北慕城南 提交于 2019-12-02 13:19:46

I you created your cell programmatically, then you can resize the cell programmatically depends on the size of UILabel Content.

In my case Label font is UIFont.systemFont(ofSize: 15), minimum TableViewCell height is 50, arrLabel1 and arrLabel2 will be the content of Labels.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrLable1.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .default, reuseIdentifier: "\(indexPath.row)")

    let lable1 = UILabel(frame: CGRect(x: 10, y: 10, width: view.frame.size.width - 20, height: 0))
    lable1.numberOfLines = 0
    lable1.font = UIFont.systemFont(ofSize: 15)
    lable1.text = arrLable1[indexPath.row]
    lable1.sizeToFit()
    cell.addSubview(lable1)

    let lable2 = UILabel(frame: CGRect(x: 10, y: lable1.frame.origin.y + lable1.frame.size.height + 10 , width: view.frame.size.width - 20, height: 0))
    lable2.numberOfLines = 0
    lable2.font = UIFont.systemFont(ofSize: 15)
    lable2.text = arrLable2[indexPath.row]
    lable2.sizeToFit()
    cell.addSubview(lable2)

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath)
    -> CGFloat {

    let boundingRect1 = arrLable1[indexPath.row].boundingRect(with: CGSize(width: view.frame.size.width - 40 , height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin,attributes:[ NSFontAttributeName : UIFont.systemFont(ofSize: 15)] ,context: nil)

    let boundingRect2 = arrLable2[indexPath.row].boundingRect(with: CGSize(width: view.frame.size.width - 40 , height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin,attributes:[ NSFontAttributeName : UIFont.systemFont(ofSize: 15)] ,context: nil)

    guard boundingRect1.height + boundingRect2.height + 30 > 50 else {
        return 50
    }

    return boundingRect1.height + boundingRect2.height + 30
}

Set Label numberOfLines to 0

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