iOS8 AutoLayout问题

时间:2014-09-18 13:55:52

标签: autolayout ios8

我在iOS8中遇到AutoLayout问题。我使用下面的代码来设置AutoLayout,当第一次加载视图时它的工作文件,当我点击后退按钮并再次进入视图时AutoLayout没有设置,我的按钮和标签都显示在屏幕的左上角位置。

以下是代码:

[btnCancel setTranslatesAutoresizingMaskIntoConstraints:NO];
[lblInfo setTranslatesAutoresizingMaskIntoConstraints:NO];


 [self setLayoutConstraints:@"V:[btnCancel(==50)]" andHorizontal:@"H:[btnCancel(==100)]" widthConstant:widthConstant heightConstant:heightConstant-80 dictionaty:NSDictionaryOfVariableBindings(btnCancel) forSubview:btnCancel];

 [self setLayoutConstraints:@"V:[lblInfo(==50)]" andHorizontal:@"H:[lblInfo(==310)]" widthConstant:widthConstant heightConstant:heightConstant-10 dictionaty:NSDictionaryOfVariableBindings(lblInfo) forSubview:lblInfo];

-(void)setLayoutConstraints:(NSString*)Vformat andHorizontal:(NSString*)Hformat widthConstant:(float)widthConst heightConstant:(float)heightConst dictionaty:(NSDictionary*)NSDictionaryOfVariableBindings forSubview:(UIView*)subview
{
    NSMutableArray *layoutConstraints;
    layoutConstraints = [NSMutableArray arrayWithArray:[NSLayoutConstraint constraintsWithVisualFormat:Vformat                                                                                                                       options:0 metrics:nil views:NSDictionaryOfVariableBindings]];
    [layoutConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:Hformat options:0 metrics:nil views:NSDictionaryOfVariableBindings]];

    NSLayoutConstraint *textFieldCenterConstraint = [NSLayoutConstraint constraintWithItem:subview attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute: NSLayoutAttributeCenterX multiplier:1.0 constant:widthConst];

    NSLayoutConstraint *textFieldBottomConstraint = [NSLayoutConstraint constraintWithItem:subview attribute:NSLayoutAttributeBottomMargin relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottomMargin multiplier:1.0 constant:heightConst];
    [self.view addConstraints:layoutConstraints];
    [self.view addConstraints:@[textFieldCenterConstraint,textFieldBottomConstraint]];

}

1 个答案:

答案 0 :(得分:0)

请务必在适当的地方致电setLayoutConstraints,例如ViewDidLoadViewDidAppear。另请尝试使用updateConstraintsIfNeeded。希望这会有所帮助。