如何根据内容调整文字标签的高度

时间:2019-04-10 03:08:21

标签: ios swift

class MojoCell :UITableViewCell{ // cell for Mojo    

@IBOutlet weak var height: NSLayoutConstraint!
@IBOutlet weak var qNumber: UILabel!
@IBOutlet weak var question: UILabel!
@IBOutlet weak var answer: UISegmentedControl!

func configure(_ mojo: MojoModel) {

    self.qNumber.text = mojo.questionNumber

    let text :String = "123456789-123456789-123456789-1234567889-123456789"
    self.question.sizeToFit()
    question.numberOfLines = 0
    question.lineBreakMode = NSLineBreakMode.byWordWrapping
    question.text = text
    question.sizeToFit()      
}

我使用了上面的代码根据UIlabel的内容来调整标签的高度。但是,它不能正常工作。它仅显示文本的一部分。

How It looks lie on X-CODE  How It looks lie on Simulator

2 个答案:

答案 0 :(得分:0)

UITableView具有automaticDimension。它将使您的行变得动态,您无需指定 heightForRowAt

您需要输入 estimatedRow height =“放入行高” 。然后在 rowHeight = UITableView.automaticDimension

在您的代码中尝试使用此方法将对您有用。 如果您不懂上述代码,请尝试以下方法:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return "put your estimated height for row"
    }

答案 1 :(得分:0)

func configure(_ mojo: MojoModel)

中使用以下代码
 templabel.text = "Your text here" <br/>
 templabel.textAlignment = .center <br/>
 templabel.frame = CGRect(x:0,y:0,width:templabel.intrinsicContentSize.width,height:templabel.intrinsicContentSize.width)
相关问题