我以编程方式构建所有对象和标签,并有一个名为 setupLayout()
的函数看起来像这样:
private func setupLayout() {
//The Image that presents the Logo of the chosen cryptocurrency.
view.addSubview(cryptoIconImage)
cryptoIconImage.translatesAutoresizingMaskIntoConstraints = false
cryptoIconImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
cryptoIconImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
cryptoIconImage.widthAnchor.constraint(equalToConstant: 60).isActive = true
cryptoIconImage.heightAnchor.constraint(equalToConstant: 60).isActive = true
//The Label that presents the name of the chosen cryptocurrency.
view.addSubview(cryptoLabel)
cryptoLabel.translatesAutoresizingMaskIntoConstraints = false
cryptoLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
cryptoLabel.topAnchor.constraint(equalTo: cryptoIconImage.bottomAnchor, constant: 10).isActive = true
cryptoLabel.font = customFont?.withSize(32)
}
这可以使布局保持美观且居中,并且非常适合肖像,并且也适用于风景。问题是在横向时,我不想让元素再居中,我想将一些元素移动到屏幕的左侧,一些移动到右侧(我没有显示设置中的所有项目)任何其他答案对于这个问题似乎都使用 Storyboard,我发现可以使用以下方法:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let orient = UIApplication.shared.statusBarOrientation
print(orient)
switch orient {
case .portrait:
print("Portrait")
break
// Do something
default:
print("LandScape")
// Do something else
self.landscapeLayout()
break
}
}
但我不确定应该如何更改删除和添加新约束,以便在来回时顺利工作。我考虑过有一个横向布局函数(),例如:
private func landscapeLayout() {
view.addSubview(cryptoIconImage)
cryptoIconImage.translatesAutoresizingMaskIntoConstraints = false
//Removing centerXAnchor
cryptoIconImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = false
cryptoIconImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
cryptoIconImage.widthAnchor.constraint(equalToConstant: 60).isActive = true
cryptoIconImage.heightAnchor.constraint(equalToConstant: 60).isActive = true
//Putting it to the left side
cryptoIconImage.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
}
但这给我带来了拉伸(stretch)等方面的问题,以及在添加新标签内容时删除标签内容的问题。我应该如何在纵向和横向之间拥有 2 个独立的布局?
最佳答案
你可以这样做:
声明变量来保存约束。
var cryptoIconImageCenterXWhenPortrait : NSLayoutConstraint?
var cryptoIconImageCenterXWhenLandscape : NSLayoutConstraint?
定义这两个约束
cryptoIconImageCenterXWhenPortrait = cryptoIconImage.centerX.constraint(equalTo: window.centerX)
cryptoIconImageCenterXWhenLandscape = cryptoIconImage.centerX.constraint(equalTo: window.centerX, constant: -20)
相应地激活它们
If Landscape {
cryptoIconImageCenterXWhenPortrait.isActive = false
cryptoIconImageCenterXWhenLandscape.isActive = true
} else If Portrait {
cryptoIconImageCenterXWhenPortrait.isActive = true
cryptoIconImageCenterXWhenLandscape.isActive = false
}
关于ios - 如何以编程方式根据纵向/横向更改布局约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52483560/