启用自动布局时如何使用自定义布局代码

时间:2015-07-17 07:15:52

标签: ios autolayout

在这种情况下,我在界面构建器中使用自动布局构建了大部分界面,但是有一个子视图非常复杂,我宁愿用自定义代码进行布局,我在文档中找到了我可以覆盖layoutSubviews()以实现我的自定义代码

“子类可以根据需要覆盖此方法,以执行更精确的子视图布局。只有当子视图的自动调整和基于约束的行为不提供您想要的行为时,才应覆盖此方法。您可以使用您的实现直接设置子视图的框架矩形。“

但我发现当我设置子视图的框架时,它只是没有任何效果,我认为自动布局系统的交互有问题。但是,任何人都可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:0)

启用自动布局时,iOS系统会忽略您为设置框架编写的任何代码。

这就是我现在正常构建我的UI的方式:

-(void)viewDidLoad
{
    [self initViews];
    [self initConstraints];
}

-(void)initViews
{
    // --------------------------------------------
    // The default init method calls initWithFrame: 
    // method and passes it a CGRectZero
    // --------------------------------------------
    self.textLabel = [[UILabel alloc] init]; 
    self.textLabel.text = @"Hello World!";

    [self.view addSubview:self.textLabel];
}

-(void)initConstraints
{
    // this line will cause any setFrame: calls to be ignored
    self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;

    id views = @{
                   @"textLabel": self.textLabel
               };

    // horizontal constraint
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[textLabel]|" options:0 metrics:nil views:views]];

    // vertical constraint
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[textLabel]|" options:0 metrics:nil views:views]];
}

例如,如果您需要更改textLabel的位置,则需要在类中声明NSLayoutConstraint属性:

@property (nonatomic, strong) NSLayoutConstraint *textLabelTopConstraint;

然后将约束代码修改为:

-(void)initConstraints
{
    self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;

    id views = @{
                   @"textLabel": self.textLabel
               };

    // horizontal constraint
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[textLabel]|" options:0 metrics:nil views:views]];

    // vertical constraint

    // --------------------------------------------
    // Note the constant value, you'll update this
    // later and tell the UI to relayout.
    // --------------------------------------------
    self.textLabelTopConstraint = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];

    // note theres no 's' after addConstraint
    [self.view addConstraint:self.textLabelTopConstraint];


}

当您点按按钮并想要更改textLabel的顶部位置时:

-(void)buttonTappedMethod
{
    // tell textLabel it should be offset 50 pixels from the top
    self.textLabelTopConstraint.constant = 50;

    // --------------------------------------------------------------------
    // wrap the layout command inside a UIView animation block to
    // see the textLabel animate down rather than instantly appear there
    // --------------------------------------------------------------------
    [UIView animateWithDuration:0.5 animations:^{

        [self.view layoutIfNeeded];

    }];
}