在捏合手势时减小屏幕上UIButtons的大小

时间:2015-03-29 18:19:04

标签: ios uigesturerecognizer uipinchgesturerecognizer

我屏幕上有几个UIButtons。如果发生捏合手势,我想减小按钮的大小(如缩小效果)并添加更多按钮。我该如何实现它?

1 个答案:

答案 0 :(得分:1)

我在StackOverflow上直接输入这个,所以可能会有拼写错误。

这些功能留作OP的练习:

  1. 连续捏合累积缩小。您必须拥有另一个私有财产才能保留当前的比例值。
  2. 在缩小效果后添加新按钮。
  3. 代码:

    @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