Xcode不允许视图保持水平居中

时间:2016-08-19 06:26:22

标签: ios swift2 constraints xcode-storyboard ios-autolayout

好吧,我有这个奇怪的问题(因为我以前从未见过这样的错误),我在我的视图中有一个Textfield,我正在用两边的动画扩展它的宽度(尾随和领先)但是问题这是它唯一从一侧扩展(尾随或领先)

我的代码:

VIewController类

@IBOutlet var constraint1: NSLayoutConstraint! // textfield's leading constraint 
@IBOutlet var constraint2: NSLayoutConstraint! // textfield's trailing constraint 

    viewDidload(){........}

    @IBAction func editingBegin(sender: AnyObject) {

    fullnameTextField.layer.cornerRadius = 0
    fullnameTextField.clipsToBounds = false
    self.constraint2.constant = -16 // here i'm expanding the width by setting constant of my Textfield
    self.constraint1.constant = -16
    UIView.animateWithDuration(duration) {
        self.fullnameTextField.layoutIfNeeded()
    }
}

我的NSlog错误:

    Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x155e77fb0 UITextField:0x155d85e40.trailing == UIView:0x155e46800.trailingMargin>",
    "<NSLayoutConstraint:0x1546b02b0 UITextField:0x155d85e40.leading == UIView:0x155e46800.leadingMargin - 16>",
    "<NSLayoutConstraint:0x1546447e0 UITextField:0x155d85e40.centerX == UIView:0x155e46800.centerX>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x1546447e0 UITextField:0x155d85e40.centerX == UIView:0x155e46800.centerX>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

这是我的故事板,我正在设置约束

enter image description here

奇怪的是,我在另一个View控制器上做同样的事情,并且它在那里工作但不在这里,我检查了每个约束它们是否正确,并且NSLog错误也出现在那个ViewController中(其中上面是工作正常)

任何人都有任何线索在这里错了吗?请让我知道它如此令人沮丧

我的ViewController的代码http://pastebin.com/BvfEvzPE

3 个答案:

答案 0 :(得分:1)

尝试删除AlignX约束;因为您已经处于领先和拖尾限制因此不需要AlignX。

您可以从此处下载示例代码并与您的代码进行比较;

http://www.filedropper.com/tst

答案 1 :(得分:1)

首先,正如@Shoaib所说,删除Center.x约束。中心X +宽度或前导+尾随就足够了。

但即便如此,布局引擎已经为您打破了Center.x约束,所有这些都应该按原样运行。但是,根据日志消息判断,只修改了“前导”约束(具有常量-16)。 “尾随”似乎没有被修改。 确保您的IBOutlet连接两个约束。

更新:实际上,网点应该没问题,因为它是Swift,否则会崩溃。我建议逐行浏览代码并查看何时出现破坏约束日志消息。

UPDATE 2 (来自评论):您确定视图的顺序在约束中是否正确?我的意思是,根据哪个视图是第一个视图,哪个是第二个视图,您需要将常量设置为+16或-16。尝试使用+/-,因为它比转到故事板并切换视图顺序更快。也许你应该为其中一个约束指定+16。

答案 2 :(得分:1)

您可以尝试将CentreX约束的优先级更改为999

enter image description here

点击修改选项,您可以将优先级更改为999

希望它有效!