如何以编程方式为iPhone SE和iPhone 5S编写自动布局?

时间:2018-10-23 19:49:52

标签: ios swift autolayout

我正在以编程方式使用自动布局来布局我的视图,问题是它在iPhone 6s plus上运行良好,但在其他屏幕上(例如iPhone SE,iPhone 5s甚至X)不能很好地渲染。下面是我的代码:

//OK button
view.addSubview(btnOk)
    btnOk.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
    btnOk.topAnchor.constraint(equalTo: lblRateUsDesc.bottomAnchor, constant: 40).isActive = true
    btnOk.widthAnchor.constraint(equalToConstant: 150).isActive = true
    btnOk.heightAnchor.constraint(equalToConstant: 55).isActive = true

//Later


view.addSubview(btnLater)
    btnLater.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
    btnLater.topAnchor.constraint(equalTo: lblRateUsDesc.bottomAnchor, constant: 40).isActive = true
    btnLater.widthAnchor.constraint(equalToConstant: 150).isActive = true
    btnLater.heightAnchor.constraint(equalToConstant: 55).isActive = true

这是iPhone SE渲染的方式This is how iPhone SE renders it

这是iPhone X渲染的方式This is how iPhone X renders it iPhone 6s plus呈现了它,这是我的首选布局iPhone 6s plus renders it and it is my preferred layout

1 个答案:

答案 0 :(得分:1)

问题在这里:

btnOk.widthAnchor.constraint(equalToConstant: 150).isActive = true

iPhone X和iPhone SE 5s屏幕狭窄。您不应将约束添加到width属性。我建议您将这些按钮嵌入到堆栈视图中。

iPhone 5s的屏幕宽度为320 pt。两个宽度为150磅的按钮的总宽度为300磅。左20点以获取空白和边距。那还不够。这就是重叠的原因。