Search code examples
iosswiftalignmentuilabeluitextview

UITextView and UILabel aligned in a row in swift


I have a UITextView and a UILabel which should align in a row. The textView is multi-line and its width should be aligned according to the label. The label is single-line but also variable in its width. But the width of the label should have a higher priority than the width of the textView. Now the problem is, that it looks like the textView is layed out to fit and the label has to deal with the space that's left:

there should be "99" displayed right of the chat bubble

Here is another example, but this time the text in the textView is short enough to fit, so that the label is displayed correctly:

enter image description here

So how can I force the label to be layout first, and after that, the textView can use the space thats left (which is no problem, since it's multi-line)?

initialization of the items:

let captionTextView: UITextView = {
    let textView = UITextView()
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.text = ""
    textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0)
    textView.textColor = .white
    textView.backgroundColor = .green
    textView.font = .systemFont(ofSize: 16)
    textView.isScrollEnabled = false
    textView.sizeToFit()
    return textView
}()

///////////////////////////////////
//Comments
var commentsIcon: UIButton = {
    let cb = UIButton()
    cb.setImage(#imageLiteral(resourceName: "chatBubble"), for: .normal)
    return cb
}()
var commentsTextLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "99"
    label.textColor = .white
    label.backgroundColor = .green
    label.font = .systemFont(ofSize: 14)
    label.sizeToFit()
    label.numberOfLines = 1
    return label
}()

layout details after adding the subviews:

//horizontal constraints

self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]-5-[v1]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": captionTextView, "v1": commentsIcon]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v0(15)]-4-[v1]-5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": commentsIcon, "v1": commentsTextLabel]))

Solution

  • You need to adjust the contentCompressionResistancePriority and contentHuggingPriority on both your label and textView.

    The label should have a higher contentCompressionResistancePriority than the textView