我有一个简单的自定义UIView(屏幕截图中带有白色背景的视图),它使用xib和自UIView派生的自定义类。

ios - 如何根据其内容自动设置自定义UIView宽度?-LMLPHP

在内部,只有UILabel和位于同一行蚂蚁上的按钮就可以了。

按钮的大小是固定的。
标签的宽度必须根据其内容进行调整。

我想要的是:
-使标签的大小适合其内容
-始终在标签之后设置按钮的位置
-使风俗适应其内容

像这样 :

ios - 如何根据其内容自动设置自定义UIView宽度?-LMLPHP

我该怎么做呢?

添加内容:

class Keyword: UIView {

@IBOutlet weak var label: UILabel!
@IBOutlet var contentView: UIView!

override init(frame: CGRect) {
    super .init(frame: frame)
    commonInit()
}

required init?(coder aDecoder: NSCoder) {
    super .init(coder: aDecoder)
    commonInit()
}

fileprivate func commonInit() {
    Bundle.main.loadNibNamed("Keyword", owner: self, options: nil)
    addSubview(contentView)
    contentView.frame = self.bounds
}

override var intrinsicContentSize: CGSize {
    let height = CGFloat(21)
    return CGSize(width: UIViewNoIntrinsicMetric, height: height)
}

/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
    // Drawing code
}
*/

}

UILabel约束:

ios - 如何根据其内容自动设置自定义UIView宽度?-LMLPHP

勾选UIButton约束:

ios - 如何根据其内容自动设置自定义UIView宽度?-LMLPHP

最佳答案

以下扩展名可用于计算标签的高度和宽度。

extension String {

//Calculate height and width for label with string
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
    let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

    return ceil(boundingBox.height)
}

func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
    let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

    return ceil(boundingBox.width)
}

}

在您的情况下,由于按钮大小是固定的,因此您可以使用上述扩展名来计算标签的宽度,并可以用于设置整个视图的宽度约束。如果标签的前导约束为8,按钮的尾随约束为8,而按钮的容器视图的尾随约束为8,则可以将视图的所需宽度计算为:
viewWidthConstraint.constant = 8+<width of string from the above extension>+8+<width of button>+8

这里唯一改变的参数将是标签的宽度。

10-02 01:05
查看更多