我有一个 UITextView 和一个 UILabel,它们应该排成一行。 textView 是多行的,其宽度应根据标签对齐。标签是单行的,但宽度也可变。但是label的宽度应该比textView的宽度有更高的优先级。 现在的问题是,看起来 textView 的布局适合并且标签必须处理剩余的空间:
这是另一个示例,但是这次 textView 中的文本足够短以适合标签,以便正确显示标签:
那么我怎样才能强制标签先布局,然后 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
}()
添加 subview 后的布局细节:
//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]))
最佳答案
您需要调整标签和 textView 上的 contentCompressionResistancePriority
和 contentHuggingPriority
。
标签应该有比 textView 更高的 contentCompressionResistancePriority
关于ios - UITextView 和 UILabel swift 排成一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42960649/