iphone 实现uilabel超链接

本文摘自:http://www.cocoachina.com/bbs/read.php?tid-60903-keyword-uilabel.html 

发个完整的超链接的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. }
posted on 2011-11-05 09:50  wtq  阅读(3271)  评论(0编辑  收藏  举报