【发布时间】:2020-08-28 18:57:15
【问题描述】:
我创建了一个视图控制器,顶部有一个分段控制器。当您点击分段控制器时,它只是充当一个按钮,并通过调用将其更改为相应尺寸的函数来更改控制器内部的 imageView 是纵向模式还是横向模式。
我的问题是我改变它的方式是我只是向 imageView 添加了约束,但是当更改为横向模式时,尾随约束并没有被删除。
而且,这是将 imageView 更改为纵向的代码(imageView 已经具有顶部和底部约束):
func portraitContraints() {
NSLayoutConstraint.activate ([
// the trailing contraint
imageView.trailingAnchor.constraint(equalTo: viewContainer.safeAreaLayoutGuide.trailingAnchor, constant: -75), // this is the contraints that doesn't get removed
// the leading contraints
imageView.leadingAnchor.constraint(equalTo: viewContainer.safeAreaLayoutGuide.leadingAnchor, constant: 75
])
// the aspect ratio contraints
imageView.addConstraint(NSLayoutConstraint(item: self.imageView as Any,attribute: .height,relatedBy: .equal,toItem: self.imageView,attribute: .width,multiplier: (4.0 / 3.0),constant: 0))
}
这是将 imageView 更改为横向的代码:
func landscapeContraints() {
NSLayoutConstraint.activate([
// the trailing contraints
imageView.trailingAnchor.constraint(equalTo: viewContainer.safeAreaLayoutGuide.trailingAnchor, constant: 0),
// the leading contraint
imageView.leadingAnchor.constraint(equalTo: viewContainer.safeAreaLayoutGuide.leadingAnchor, constant: 0)
])
// the aspect ratio contraint
imageView.addConstraint(NSLayoutConstraint(item: self.imageView as Any,attribute: .height,relatedBy: .equal,toItem: self.imageView,attribute: .width,multiplier: (9.0 / 16.0),constant: 0))
}
这段代码就像一个魅力,除了唯一的问题是纵向模式的尾随约束将保留在视图上(-75 常量约束)。
人像是这样的:
【问题讨论】:
标签: ios swift xcode uiimageview constraints