如何使用 SnapKit 为 UITextField 和 UILabel 设置约束?

Ale*_*ach 2 autolayout swift snapkit

我有一个 [[TextField 需要最大可用宽度----]offset(10.0)][Label]]。我想将 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()
}
Run Code Online (Sandbox Code Playgroud)

Sh_*_*han 5

你需要

label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentCompressionResistancePriority(.required, for: .horizontal)
Run Code Online (Sandbox Code Playgroud)

您也可以完全删除这两行,因为默认情况下文本字段的ContentHuggingPriority&&ContentCompressionResistancePriority低于 label 的默认值,而且文本字段没有内在大小