1. 程式人生 > >UILabel點選實現超連結

UILabel點選實現超連結

為了例項化咱們的Label時必須做點啥.. 先來個協議.
.h檔案
複製程式碼
  1. #import <Foundation/Foundation.h>
  2. @class MyLabel;
  3. @protocol MyLabelDelegate <NSObject>
  4. @required
  5. - (void)myLabel:(MyLabel *)myLabel touchesWtihTag:(NSInteger)tag;
  6. @end

新建類,繼承UILabel.
複製程式碼
  1. @interface MyLabel : UILabel {
  2.     id <MyLabelDelegate> delegate;
  3. }
  4. @property (nonatomic, assign) id <MyLabelDelegate> delegate;
  5. - (id)initWithFrame:(CGRect)frame;
  6. @end

.m檔案
複製程式碼
  1. #import "MyLabel.h"
  2. #define FONTSIZE 13
  3. #define COLOR(R,G,B,A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]
  4. @implementation MyLabel
  5. @synthesize delegate;
  6. // 設定換行模式,字型大小,背景色,文字顏色,開啟與使用者互動功能,設定label行數,0為不限制
  7. - (id)initWithFrame:(CGRect)frame {
  8.     if (self = [super initWithFrame:frame])
  9.     {
  10.         [self setLineBreakMode:UILineBreakModeWordWrap|UILineBreakModeTailTruncation];
  11.         [self setFont:[UIFont systemFontOfSize:FONTSIZE]];
  12.         [self setBackgroundColor:[UIColor clearColor]];
  13.         [self setTextColor:COLOR(59,136,195,1.0)];
  14.         [self setUserInteractionEnabled:YES];
  15.         [self setNumberOfLines:0];
  16.     }
  17.     return self;
  18. }
  19. // 點選該label的時候, 來個高亮顯示
  20. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  21.     [self setTextColor:[UIColor whiteColor]];
  22. }
  23. // 還原label顏色,獲取手指離開螢幕時的座標點, 在label範圍內的話就可以觸發自定義的操作
  24. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  25.     [self setTextColor:COLOR(59,136,195,1.0)];
  26.     UITouch *touch = [touches anyObject];
  27.     CGPoint points = [touch locationInView:self];
  28.     if (points.x >= self.frame.origin.x && points.y >= self.frame.origin.x && points.x <= self.frame.size.width && points.y <= self.frame.size.height)
  29.     {
  30.         [delegate myLabel:self touchesWtihTag:self.tag];
  31.     }
  32. }
  33. - (void)dealloc {
  34.     [super dealloc];
  35. }
  36. @end

例項化:
複製程式碼
  1. MyLabel *webSite = [[MyLabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
  2. [webSite setText:@"http://www.google.com"];
  3. [webSite  setDelegate:self];
  4. [self.view addSubview:webSite];
  5. [webSite  release];
  6. #pragma mark MyLabel Delegate Methods
  7. // myLabel是你的MyLabel委託的例項, tag是該例項的tag值, 有點多餘, 哈哈
  8. - (void)myLabel:(MyLabel *)myLabel touchesWtihTag:(NSInteger)tag {
  9.     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:webSite.text]];
  10. }