UITextField 未归档 UIStackView 内的可用宽度

Fez*_*ezZ 4 uitextfield uikit ios swift uistackview

我想在屏幕的左右边缘放置两个带有图像的按钮,并UITextField在它们之间插入一个。一切都storyboard很好,但我需要以编程方式完成。

来源:

class SecondViewController: UIViewController {


override func loadView() {
    super.loadView()
    self.view.backgroundColor = .white
    let leftButton = UIButton()
    leftButton.setImage(UIImage(named: "first"), for: .normal)
    leftButton.setTitle("", for: .normal)
    
    let rightButton = UIButton()
    rightButton.setImage(UIImage(named: "second"), for: .normal)
    rightButton.setTitle("", for: .normal)
    
    let textField = UITextField()
    textField.placeholder = "clear"
    textField.borderStyle = .roundedRect
    textField.contentHorizontalAlignment = .left
    textField.contentVerticalAlignment = .center
    
    let stackView = UIStackView()
    
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.alignment = .fill
    stackView.distribution = .fill
    stackView.axis = .horizontal
    stackView.spacing = 15

    stackView.addArrangedSubview(leftButton)
    stackView.addArrangedSubview(textField)
    stackView.addArrangedSubview(rightButton)
    
    self.view.addSubview(stackView)
    
    NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 15).isActive = true
    NSLayoutConstraint(item: stackView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: -15).isActive = true
    NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 50).isActive = true
    
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}
Run Code Online (Sandbox Code Playgroud)

我需要像第一张图片那样的结果。

我需要这样的结果

但结果我得了第二。 但得到了这个

我做错了什么 ?

mat*_*att 6

你有一个基本的约束模糊性。只需切换到视图调试器,您就可以轻松发现这一点;您会看到三个感叹号警告您存在问题。布局引擎不会神奇地知道应该允许三个视图中的哪一个水平拉伸。你必须告诉它:

textField.setContentHuggingPriority(UILayoutPriority(249), for: .horizontal)
Run Code Online (Sandbox Code Playgroud)