Search code examples
swiftautolayoutsnapkit

How to setup constraints with SnapKit for UITextField and UILabel?


I have a [[TextField need max available width----]offset(10.0)][Label]]. I want to setup TextFeild pin to left and shrink all available space without label trimming and setup label to pin right and get minimal fit size.

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()
}

Solution

  • You need

    label.setContentHuggingPriority(.required, for: .horizontal)
    label.setContentCompressionResistancePriority(.required, for: .horizontal)
    

    Also you can completely remove these 2 lines as by default textfield's ContentHuggingPriority && ContentCompressionResistancePriority is lower than the default for label , plus the textfield has no intrinsic size