UIPinchGestureRecognizer 為一個連續性的手勢辨識器,因為它會在 Pinch 期間不斷的去呼叫它的動作方法。
我們來看看程式碼:
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *lable;
@property (assign, nonatomic) CGFloat initialFontSize;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self
action:@selector(doPinch:)];
[self.view addGestureRecognizer:pinch];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
_lable = nil;
}
#pragma mark - Added methods
- (void)doPinch:(UIPinchGestureRecognizer *)pinch {
if (pinch.state == UIGestureRecognizerStateBegan) {
_initialFontSize = _lable.font.pointSize;
} else {
_lable.font = [_lable.font fontWithSize:_initialFontSize * pinch.scale];
}
}
@end
在 viewDidLoad 裡,我們設定了一個 UIPinchGestureRecognizer,並告訴它發生此動作時透過 doPinch: 方法來通知我們。在 doPinch: 裡,我們先查看 Pinch 的狀態是否處於剛開始階段,如果是,就將目前的字體大小儲存起來。
若不是(Pinch 已在進行中),就用儲存的字體大小,以及目前 Pinch 的幅度(scale)來計算新的字體大小。