MASExampleRemakeView.m 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // MASExampleRemakeView.m
  3. // Masonry iOS Examples
  4. //
  5. // Created by Sam Symons on 2014-06-22.
  6. // Copyright (c) 2014 Jonas Budelmann. All rights reserved.
  7. //
  8. #import "MASExampleRemakeView.h"
  9. @interface MASExampleRemakeView ()
  10. @property (nonatomic, strong) UIButton *movingButton;
  11. @property (nonatomic, assign) BOOL topLeft;
  12. - (void)toggleButtonPosition;
  13. @end
  14. @implementation MASExampleRemakeView
  15. - (id)init {
  16. self = [super init];
  17. if (!self) return nil;
  18. self.movingButton = [UIButton buttonWithType:UIButtonTypeSystem];
  19. [self.movingButton setTitle:@"Move Me!" forState:UIControlStateNormal];
  20. self.movingButton.layer.borderColor = UIColor.greenColor.CGColor;
  21. self.movingButton.layer.borderWidth = 3;
  22. [self.movingButton addTarget:self action:@selector(toggleButtonPosition) forControlEvents:UIControlEventTouchUpInside];
  23. [self addSubview:self.movingButton];
  24. self.topLeft = YES;
  25. return self;
  26. }
  27. + (BOOL)requiresConstraintBasedLayout
  28. {
  29. return YES;
  30. }
  31. // this is Apple's recommended place for adding/updating constraints
  32. - (void)updateConstraints {
  33. [self.movingButton remakeConstraints:^(MASConstraintMaker *make) {
  34. make.width.equalTo(@(100));
  35. make.height.equalTo(@(100));
  36. if (self.topLeft) {
  37. make.left.equalTo(self.left).with.offset(10);
  38. make.top.equalTo(self.top).with.offset(10);
  39. }
  40. else {
  41. make.bottom.equalTo(self.bottom).with.offset(-10);
  42. make.right.equalTo(self.right).with.offset(-10);
  43. }
  44. }];
  45. //according to apple super should be called at end of method
  46. [super updateConstraints];
  47. }
  48. - (void)toggleButtonPosition {
  49. self.topLeft = !self.topLeft;
  50. // tell constraints they need updating
  51. [self setNeedsUpdateConstraints];
  52. // update constraints now so we can animate the change
  53. [self updateConstraintsIfNeeded];
  54. [UIView animateWithDuration:0.4 animations:^{
  55. [self layoutIfNeeded];
  56. }];
  57. }
  58. @end