能夠觸發點擊事件並變色的UILabel
post
誰說UILabel不可以當作button處理點擊事件呢?今天,筆者就像你們提供一個改造過的,可以觸發點擊事件並變色的UILabel:)atom
效果圖:spa
還能當作計時器用囧:code
源碼以下:blog
TapLabel.h 與 TapLabel.m事件
// // TapLabel.h // TapLabel // // Copyright (c) 2014年 Y.X. All rights reserved. // #import <UIKit/UIKit.h> @class TapLabel; @protocol TapLabelDelegate <NSObject> - (void)tapLabelEvent:(TapLabel *)label; @end @interface TapLabel : UILabel @property (nonatomic, assign) id<TapLabelDelegate> delegate; // 協議 @property (nonatomic, strong) NSString *notificationName; // 設置通知中心名字 @property (nonatomic, strong) NSDictionary *metaData; // 元數據 @end
// // TapLabel.m // TapLabel // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "TapLabel.h" @implementation TapLabel - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.userInteractionEnabled = YES; UILongPressGestureRecognizer *tap = \ [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(labelEvent:)]; tap.minimumPressDuration = 0.01f; [self addGestureRecognizer:tap]; } return self; } - (void)labelEvent:(UILongPressGestureRecognizer *)gesture { // 獲取到座標值 CGPoint locationPoint = [gesture locationInView:self]; // 狀態1 if (gesture.state == UIGestureRecognizerStateBegan) { self.highlighted = YES; } // 狀態2 if(gesture.state == UIGestureRecognizerStateChanged) { if (locationPoint.x <= self.bounds.size.width && locationPoint.x >= 0 && locationPoint.y <= self.bounds.size.height && locationPoint.y >= 0) { self.highlighted = YES; } else { self.highlighted = NO; } } // 狀態3 if (gesture.state == UIGestureRecognizerStateEnded) { if (locationPoint.x <= self.bounds.size.width && locationPoint.x >= 0 && locationPoint.y <= self.bounds.size.height && locationPoint.y >= 0) { if (_delegate) { [_delegate tapLabelEvent:self]; } if (_notificationName) { [[NSNotificationCenter defaultCenter] postNotificationName:_notificationName object:nil userInfo:@{@"TapLabel": self}]; } } self.highlighted = NO; } } @end
使用時的源碼:get
// // RootViewController.m // TapLabel // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "RootViewController.h" #import "TapLabel.h" @interface RootViewController ()<TapLabelDelegate> @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; TapLabel *tap = [[TapLabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)]; tap.textAlignment = NSTextAlignmentCenter; tap.center = self.view.center; tap.text = @"YouXianMing"; tap.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:18]; tap.delegate = self; tap.metaData = @{@"name": @"YouXianMing"}; tap.highlightedTextColor = [UIColor redColor]; [self.view addSubview:tap]; } - (void)tapLabelEvent:(TapLabel *)label { NSLog(@"%@", label.metaData); } @end
原理解析:源碼
1. 在初始化的時候後添加了手勢處理:it
2. 精確計算手勢的3種狀態io
3. UILabel自帶了highlightedTextColor:)
原理就是這麼簡單呢:)