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

How to setup constraints with SnapKit for UITextField and UILabel?

我有一个[[TextField need max available width----]offset(10.0)][Label]]。我想将 TextFeild 固定到左侧并缩小所有可用的 space 而不进行标签修剪,并将标签设置到固定到右侧并获得最小的适合尺寸。

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

你需要

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

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

实现下面的演示。

标签可以通过下面的属性自动增加高度。 (swift 5)

label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping

当你设置
时,可以让super view的高度同时同步 超级视图的高度与标签相同。

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