如何覆盖约束

时间:2019-02-15 21:37:37

标签: ios objective-c xcode

我有一个UIButton像这样受限于父视图:

[myButton constrainToParentView:NSLayoutAttributeCenterX];

以及稍后在我的代码中,我想将约束更改为:

[myButton constrainToParentView:NSLayoutAttributeLeading spaced:24];

但是当第二行运行时,它不会覆盖第一个约束。相反,两个约束都存在。如何覆盖第一个约束?我读到您必须将约束设置为一个属性,但是我找不到针对我的情况进行此操作的任何信息。

1 个答案:

答案 0 :(得分:1)

您可能不想使用constrainToParentView当前使用的任何方法或扩展名-或需要对其进行编辑以允许保存对约束的引用。

这是一个简单的示例,直接使用约束方法。非常简单,注释应该清楚。它创建一个按钮,将其水平居中,然后在每次点击时在前导约束和中心约束之间交换。

// SwapConstraintsViewController.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface SwapConstraintsViewController : UIViewController

@end

NS_ASSUME_NONNULL_END

// SwapConstraintsViewController.m

#import "SwapConstraintsViewController.h"

@interface SwapConstraintsViewController ()

@property (strong, nonatomic) UIButton *myButton;

@property (strong, nonatomic) NSLayoutConstraint *centerXLayoutConstraint;
@property (strong, nonatomic) NSLayoutConstraint *leadingLayoutConstraint;

@end

@implementation SwapConstraintsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _myButton = [UIButton new];
    _myButton.translatesAutoresizingMaskIntoConstraints = NO;
    _myButton.backgroundColor = [UIColor redColor];
    [_myButton setTitle:@"Test Button" forState:UIControlStateNormal];

    [self.view addSubview:_myButton];

    // constrain the button 100-pts from the top of the view
    [_myButton.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:100.0].active = YES;

    // create centerX constraint
    _centerXLayoutConstraint = [_myButton.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor constant:0.0];

    // create leading constraint
    _leadingLayoutConstraint = [_myButton.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:24.0];

    // activate centerX constraint
    _centerXLayoutConstraint.active = YES;

    [_myButton addTarget:self action:@selector(didTap:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)didTap:(id)sender {

    if ([_centerXLayoutConstraint isActive]) {
        // de-activate center first, then activate leading
        _centerXLayoutConstraint.active = NO;
        _leadingLayoutConstraint.active = YES;
    } else {
        // de-activate leading first, then activate center
        _leadingLayoutConstraint.active = NO;
        _centerXLayoutConstraint.active = YES;
    }

}

@end