Skip to content

Instantly share code, notes, and snippets.

@jeffbailey
Created August 10, 2014 20:51
Show Gist options
  • Save jeffbailey/16dd41c39374ff90aead to your computer and use it in GitHub Desktop.
Save jeffbailey/16dd41c39374ff90aead to your computer and use it in GitHub Desktop.
Create and center a button using Autolayout
self.insertTextButton = [UIButton buttonWithType:UIButtonTypeSystem];
[self.insertTextButton setTitle:@"Press Me" forState:UIControlStateNormal];
[self.insertTextButton sizeToFit];
self.insertTextButton.translatesAutoresizingMaskIntoConstraints = NO;
[self.insertTextButton addTarget:self action:@selector(insertText) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.insertTextButton];
[self.view addConstraint: [NSLayoutConstraint constraintWithItem:self.insertTextButton
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.f constant:0.f]];
[self.view addConstraint: [NSLayoutConstraint constraintWithItem:self.insertTextButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.f constant:0.f]];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment