如何调整 UIView 的大小以适应其内容?

How do you resize a UIView to fit its contents?

我有一个 UIView,其中包含两个标签。我希望视图调整大小,以便它包含每个标签中的所有文本,但文本溢出视图。这是我的代码:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: K.reuseIdentifier, for: indexPath) as! NoteTableViewCell
       
    cell.titleLabel?.text = titleArray[indexPath.row]
    cell.mainTextLabel?.text = noteArray[indexPath.row]
    cell.titleLabel?.font = UIFont(name:"HelveticaNeue-Bold", size: 18.0)
    cell.cardView?.sizeToFit()
    cell.cardView?.layer.shadowOpacity = 1
    cell.cardView?.layer.shadowOffset = .zero
    cell.cardView?.layer.shadowRadius = 1
    cell.cardView?.layer.cornerRadius = 8
    return cell
}

结果如下:

你需要这些约束

CardView // hook it's top,bottom,leading and trailing to parent View

        |
  - titleLabel -  // hook it's top , leading and trailing to Card View  
        | 
  - mainTextLabel - // hook it's top to titleLabel , leading and trailing and bottom to Card View  
        |

并删除

cell.cardView?.sizeToFit()