我想要一个以超级视图为中心的视图,但由于此例中的内容是标签,因此视图会增长。但我不希望它增长,因为它不再适合屏幕,所以这就是为什么我左右固定。
我已经安装了一个测试视图控制器:
import UIKit
import PureLayout
final class ViewController: UIViewController {
let container: UIView = {
let container = UIView(forAutoLayout: ())
container.backgroundColor = UIColor.blackColor()
container.clipsToBounds = true
return container
}()
let label: UILabel = {
let label = UILabel(forAutoLayout: ())
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 1
label.textColor = UIColor.redColor()
label.text = "This is a very very very long message"
return label
}()
var rightView: UIView = {
let view = UIView(forAutoLayout: ())
view.backgroundColor = .redColor()
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.container.addSubview(self.label)
self.view.addSubview(self.container)
self.view.addSubview(self.rightView)
self.container.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 20)
self.container.autoAlignAxisToSuperviewAxis(.Vertical)
self.container.autoSetDimension(.Height, toSize: 36)
self.container.layer.cornerRadius = 18
self.container.autoPinEdge(.Right, toEdge: .Left, ofView: self.rightView, withOffset: -20, relation: .LessThanOrEqual)
self.container.autoPinEdgeToSuperviewEdge(.Left, withInset: 20, relation: .GreaterThanOrEqual)
self.container.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
self.label.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(10, 20, 10, 20))
self.rightView.autoPinEdgeToSuperviewEdge(.Right, withInset: 5)
self.rightView.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 20)
self.rightView.autoSetDimension(.Width, toSize: 50)
self.rightView.autoSetDimension(.Height, toSize: 60)
}
}
结果是:
为什么黑色视图不会增长,直到它不能由于左右约束?行数是1,ContentCompressionResistancePriority是否打开?
答案 0 :(得分:2)
您可以更改字体大小以适合UILabel(非多线)的宽度:
label.numberOfLines = 1;
label.adjustsFontSizeToFitWidth = true;
label.sizeToFit();
您需要动态更改高度意味着您可以执行以下操作
label.preferredMaxLayoutWidth = 500;
您可以使用上面的代码设置首选最大宽度,最好:)
答案 1 :(得分:1)
标签上的前导和尾随约束是什么,您可以将前导约束设置为大于或等于5的不等式。如果您对字体变小感到高兴,可以设置{ {1}}为YES。
答案 2 :(得分:0)
试试这个
testLabel.text = "long text......."
testLabel.numberOfLines = 0
testLabel.sizeToFit()
答案 3 :(得分:0)
在代码中设置label.numberOfLines = 0
,然后只根据您拥有的文字展开。
答案 4 :(得分:0)