Aligning multiple runtime generated UILabels in a UITableView

后端 未结 1 1660
一向
一向 2021-01-26 15:19

I have a UITableView that needs to support content by listing style something like

But the tricky part is that the amount of \"Label\" will vary wi

相关标签:
1条回答
  • 2021-01-26 16:11

    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

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