Dhruv Ramani
Dhruv Ramani

Reputation: 2643

Decrease size of UIButtons on Screen upon Pinch Gesture

I have couple of UIButtons on the screen. If a pinch gesture occurs, I want to decrease the size of the buttons (Like a zoom-out effect) and add more buttons. How would I implement it?

Upvotes: 1

Views: 335

Answers (1)

JoJo
JoJo

Reputation: 20115

I am typing this directly on StackOverflow, so there may be typos.

These features are left as an exercise for the OP:

  1. Cumulatively scaling down with successive pinches. You must have another private property to hold the current scale value.
  2. Adding new buttons after the zooming out effect.

Code:

@interface MyViewController : UIViewController
@property(nonatomic, strong) NSMutableArray* buttons;
- (void)pinched:(UIPinchGestureRecognizer*)gesture;
@end

@implementation MyViewController

- (void)loadView {
  [super loadView];
  self.buttons = [NSMutableArray array];
  for (NSUInteger i = 0; i < 3; i++) {
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(
      0.0f,
      (44.0f + 10.0f) * (CGFloat)i,
      100.0f,
      44.0f
    )];
    button.backgroundColor = [UIColor blueColor];
    [self.view addSubview:button];
    [self.buttons addObject:button];
  }
}

- (void)viewDidLoad {
  [super viewDidLoad];
  UIPinchGestureRecognizer* pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinched:)];
  [self.view addGestureRecognizer:pinch];
}

- (void)pinched:(UIPinchGestureRecognizer*)gesture {
  if (gesture.scale > 1.0) {
    return;
  }

  for (UIButton* button in self.buttons) {
    [UIView 
      animateWithDuration:1.0
      animations:^void() {
        button.transform = CGAffineTransformMakeScale(0.5, 0.5);
      }
    ];
  }
}

@end

Upvotes: 1

Related Questions