UILabel点击实现超链接

为了实例化咱们的Label时必须做点啥.. 先来个协议.
.h文件
复制代码
  1. #import
  2. @class MyLabel;
  3. @protocol MyLabelDelegate
  4. @required
  5. - (void)myLabel:(MyLabel *)myLabel touchesWtihTag:(NSInteger)tag;
  6. @end

新建类,继承UILabel.
复制代码
  1. @interface MyLabel : UILabel {
  2.     id delegate;
  3. }
  4. @property (nonatomic, assign) id 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. }

你可能感兴趣的:(UILabel点击实现超链接)