我有一个[[TextField需要最大可用宽度----]偏移量(10.0)] [标签]]。我想将TextFeild插针设置为左侧并缩小所有可用空间,而无需修剪标签,而将标签设置为插针右侧并获得最小的合适尺寸。
lazy var textField: UITextField = {
var textField = UITextField()
textField.placeholder = "Placeholder"
textField.delegate = self
textField.borderStyle = UITextField.BorderStyle.none
textField.keyboardType = UIKeyboardType.numberPad
textField.returnKeyType = UIReturnKeyType.done
textField.setContentHuggingPriority(.defaultHigh, for: .horizontal)
return textField
}()
lazy var measureLabel: UILabel = {
var label = UILabel()
label.numberOfLines = 1
label.setContentHuggingPriority(.defaultLow, for: .horizontal)
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return label
}()
measureLabel.snp.makeConstraints { (make) in
make.right.equalTo(self.snp.right)
make.centerY.equalToSuperview()
}
textField.snp.makeConstraints { (make) in
make.left.equalToSuperview()
make.right.equalTo(self.measureLabel.snp.left).offset(-10.0)
make.centerY.equalToSuperview()
}
答案 0 :(得分:1)
您需要
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentCompressionResistancePriority(.required, for: .horizontal)
您还可以完全删除这两行,因为默认情况下,文本字段的ContentHuggingPriority
&& ContentCompressionResistancePriority
小于label的默认值,并且文本字段没有固有大小
答案 1 :(得分:0)
实施以下演示。
标签可以使用以下属性自动增加高度。 (速记5)
label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
设置时可以同时使超级视图的高度同步
超级视图的高度与标签相同。
label = UILabel()
viewContainer.addSubview(label)
label.backgroundColor = UIColor.white
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.text = "hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day."
self.addSubview(label)
label.snp.makeConstraints { (make) in
let superView = viewContainer!
make.left.equalTo(superView).offset(10)
make.right.equalTo(superView).offset(-10)
make.centerY.equalTo(superView)
}
viewContainer.snp.makeConstraints { (make) in
make.centerY.equalTo(self)
make.centerX.equalTo(self)
make.left.equalTo(self).offset(10)
make.right.equalTo(self).offset(-10)
make.height.equalTo(label).offset(100)
}
下载代码:https://github.com/zgpeace/SnapkitDemo/tree/dynamicHeightLabel