ios - Swift 约束不在旋转之后

标签 ios swift uiview uibutton nslayoutconstraint

我在代码中以编程方式创建一个 UIButton,并将其限制在 ViewController 的顶部和右侧。当 ViewController 加载时,UIButton 位于屏幕上的正确位置。当我旋转设备时出现问题,约束似乎没有被采用。这是我用来创建 UIButton 的代码:

let xValue = UIScreen.mainScreen().bounds.width - 44
let closeButton = UIButton(frame: CGRect(origin: CGPoint(x: xValue, y: 0), size: CGSize(width: 44, height: 44)))

closeButton.setImage(UIImage(named: "close"), forState: .Normal)
closeButton.addTarget(self, action: "closeClicked", forControlEvents:.TouchUpInside)

self.view.addSubview(closeButton)

self.view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1, constant: 0))

我还需要做些什么来确保在方向更改后应用约束吗?

最佳答案

您不应将 frames 与约束结合使用。默认情况下,iOS 会将您的框架转换为约束,这会导致与您设置的约束发生冲突。创建按钮后,您需要调用:

对于 Swift 1.2:

closeButton.setTranslatesAutoresizingMaskIntoConstraints(false)

对于 Swift 2.0:

closeButton.translatesAutoresizingMaskIntoConstraints = false

这样 iOS 就不会尝试将您的框架转换为约束。然后您需要为按钮的宽度和高度添加两个额外的约束:

closeButton.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .Width,
  relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 44))

closeButton.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .Height,
  relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 44))

由于您的按钮不再使用框架,您可以使用以下方法创建它:

let closeButton = UIButton()

现在您的按钮将在所有设备的所有方向上固定在屏幕的右上角。

关于ios - Swift 约束不在旋转之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31256389/

相关文章:

ios - 非通用类的通用扩展?

swift 施法失败

iphone - 旋转 View 时不触发 UIInterfaceOrientationIsLandscape

ios - 如何快速转换java代码?

ios - 强制 UIWebView 的横向方向?

ios - 我们应该将所有数据存储在最新版本的 firebase 上吗?

ios - ARSCNView 截图

ios - 仅在单击按钮后显示事件指示器

swift - 以编程方式添加内容时 UIView 发生变化 - Swift

ios - 自定义 MKOverlayView 线宽