UITextView和UILabel在swift中连续排列

时间:2017-03-22 19:09:51

标签: ios swift alignment uilabel uitextview

我有一个UITextView和一个应该排成一行的UILabel。 textView是多行的,其宽度应根据标签对齐。标签是单行的,但宽度也是可变的。但标签的宽度应优先于textView的宽度。 现在的问题是,看起来textView是适合的,标签必须处理剩下的空间:

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

这是另一个例子,但这次textView中的文字足够短,以便正确显示标签:

enter image description here

那么如何强制标签首先布局,之后,textView可以使用剩下的空间(这是没有问题的,因为它的多线)?

项目的初始化:

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
}()
添加子视图后的

布局详细信息:

//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]))

1 个答案:

答案 0 :(得分:2)

您需要调整标签和textView上的contentCompressionResistancePrioritycontentHuggingPriority

标签应该比textView

contentCompressionResistancePriority