UITextField没有在UIStackView中归档可用宽度

时间:2019-06-12 17:07:16

标签: ios swift uitextfield uikit 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.
}

我需要类似第一张图片的结果。

I need result like this

但结果却是第二。 but got this

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您在基本约束上有歧义。您只需切换到View Debugger即可轻松发现这一点。您会看到三个感叹号警告您该问题。布局引擎无法神奇地知道应允许三个视图中的哪个水平伸展。您必须告诉它:

textField.setContentHuggingPriority(UILayoutPriority(249), for: .horizontal)

答案 1 :(得分:1)

设置约束,例如

NSLayoutConstraint.activate([
    stackView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50),
    stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15),
    stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15),
    stackView.heightAnchor.constraint(equalToConstant: 45),
    leftButton.widthAnchor.constraint(equalToConstant: 30), 
    rightButton.widthAnchor.constraint(equalToConstant: 30),
])

另一个小变化

rightButton.imageView?.contentMode = .scaleAspectFit
leftButton.imageView?.contentMode = .scaleAspectFit

结果

enter image description here