MASExampleRemakeView.m 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. // make sure updateConstraints gets called
  26. [self setNeedsUpdateConstraints];
  27. return self;
  28. }
  29. // this is Apple's recommended place for adding/updating constraints
  30. - (void)updateConstraints {
  31. [self.movingButton remakeConstraints:^(MASConstraintMaker *make) {
  32. make.width.equalTo(@(100));
  33. make.height.equalTo(@(100));
  34. if (self.topLeft) {
  35. make.left.equalTo(self.topLeft).with.offset(10);
  36. make.top.equalTo(self.top).with.offset(10);
  37. }
  38. else {
  39. make.bottom.equalTo(self.bottom).with.offset(-10);
  40. make.right.equalTo(self.right).with.offset(-10);
  41. }
  42. }];
  43. //according to apple super should be called at end of method
  44. [super updateConstraints];
  45. }
  46. - (void)toggleButtonPosition {
  47. self.topLeft = !self.topLeft;
  48. // tell constraints they need updating
  49. [self setNeedsUpdateConstraints];
  50. // update constraints now so we can animate the change
  51. [self updateConstraintsIfNeeded];
  52. [UIView animateWithDuration:0.4 animations:^{
  53. [self layoutIfNeeded];
  54. }];
  55. }
  56. @end