Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift约束不';不要在轮换后服用_Ios_Swift_Uiview_Uibutton_Nslayoutconstraint - Fatal编程技术网

Ios Swift约束不';不要在轮换后服用

Ios Swift约束不';不要在轮换后服用,ios,swift,uiview,uibutton,nslayoutconstraint,Ios,Swift,Uiview,Uibutton,Nslayoutconstraint,我正在代码中以编程方式创建一个ui按钮,并将其约束到ViewController的顶部和右侧。加载ViewController时,ui按钮在屏幕上处于正确位置。当我旋转设备时,问题来了,约束似乎没有被接受。下面是我用来创建ui按钮的代码: let xValue = UIScreen.mainScreen().bounds.width - 44 let closeButton = UIButton(frame: CGRect(origin: CGPoint(x: xValue, y: 0), si

我正在代码中以编程方式创建一个
ui按钮
,并将其约束到
ViewController
的顶部和右侧。加载
ViewController
时,
ui按钮在屏幕上处于正确位置。当我旋转设备时,问题来了,约束似乎没有被接受。下面是我用来创建
ui按钮的代码:

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))

是否需要执行其他操作以确保在方向更改后应用约束?

您不应将
与约束组合在一起。默认情况下,iOS会将您的帧转换为约束,这会导致与您正在设置的约束冲突。创建按钮后,您需要调用:

对于Swift 1.2:

closeButton.setTranslatesAutoresizingMaskIntoConstraints(false)
closeButton.translatesAutoresizingMaskIntoConstraints = false
对于Swift 2.0:

closeButton.setTranslatesAutoresizingMaskIntoConstraints(false)
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()

现在,您的按钮将在所有设备的所有方向上粘贴到屏幕的右上角。

您只需在segue上禁用动画(取消选中“动画”复选框),然后就无需更新约束。
编辑故事板时,可以在右面板的Segue options中找到。

您正在测试什么设备?我已经使用运行iOS 8.3的模拟器(iPad Air、iPhone 6、iPhone 6+)以及运行iOS 8.4的iPad 2和iPod 5 gen进行了测试。他们都表现出相同的行为