Centre the button in view use constraints programmatically in iOS 8

NTNT picture NTNT · Oct 18, 2014 · Viewed 8.2k times · Source

I have a subview and added 1 button. I want to add this button in the center of that view. I use Autolayout so i need to set the constraints for this button programmatically.

I tried this code but the play button is not in the center.

[self.moviePlayer.view addSubview:self.playbtn];


 self.playbtn.translatesAutoresizingMaskIntoConstraints = NO;

[self.moviePlayer.view addConstraint:[NSLayoutConstraint constraintWithItem:self.playbtn attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual
                                           toItem:self.moviePlayer.view attribute:NSLayoutAttributeCenterX multiplier:0.667 constant:0]];

Please help me to correct it. Thanks in advance.

Answer

Zhang picture Zhang · Oct 20, 2014

You can use the NSLayoutAttributeCenterX and NSLayoutAttributeCenterY attributes to center your play button like this:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self initViews];
    [self initConstraints];
}

-(void)initViews
{
    self.picture = [[UIImageView alloc] init];
    self.picture.image = [UIImage imageNamed:@"bg"];

    self.playButton = [[UIButton alloc] init];
    [self.playButton setImage:[UIImage imageNamed:@"playButton"] forState:UIControlStateNormal];

    [self.view addSubview:self.picture];
    [self.view addSubview:self.playButton];
}

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

    id views = @{
                 @"picture": self.picture,
                 @"playButton": self.playButton
                 };

    // picture constraints
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[picture]|" options:0 metrics:nil views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[picture]|" options:0 metrics:nil views:views]];


    // play button constraints

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.playButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.playButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];
}

You get something like this:

demo screenshot