超链接的UILabel教程

本文介绍如何在Objective-C中创建一个自定义标签控件,包括设置其样式、交互逻辑及委托方法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#import <Foundation/Foundation.h>
@class MyLabel;
@protocol MyLabelDelegate <NSObject>
@required
- (void)myLabel:(MyLabel *)myLabel touchesWtihTag:(NSInteger)tag;
@end

新建类,继承UILabel.

@interface MyLabel : UILabel {
    id <MyLabelDelegate> delegate;
}
@property (nonatomic, assign) id <MyLabelDelegate> delegate;
- (id)initWithFrame:(CGRect)frame;
@end

.m文件

#import "MyLabel.h"
#define FONTSIZE 13
#define COLOR(R,G,B,A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]
@implementation MyLabel
@synthesize delegate;
// 设置换行模式,字体大小,背景色,文字颜色,开启与用户交互功能,设置label行数,0为不限制
- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame])
    {
        [self setLineBreakMode:UILineBreakModeWordWrap|UILineBreakModeTailTruncation];
        [self setFont:[UIFont systemFontOfSize:FONTSIZE]];
        [self setBackgroundColor:[UIColor clearColor]];
        [self setTextColor:COLOR(59,136,195,1.0)];
        [self setUserInteractionEnabled:YES];
        [self setNumberOfLines:0];
    }
    return self;
}
// 点击该label的时候, 来个高亮显示
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self setTextColor:[UIColor whiteColor]];
}
// 还原label颜色,获取手指离开屏幕时的坐标点, 在label范围内的话就可以触发自定义的操作
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self setTextColor:COLOR(59,136,195,1.0)];
    UITouch *touch = [touches anyObject];
    CGPoint points = [touch locationInView:self];
    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)
    {
        [delegate myLabel:self touchesWtihTag:self.tag];
    }
}
- (void)dealloc {
    [super dealloc];
}
@end

实例化:

MyLabel *webSite = [[MyLabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
[webSite setText:@"http://www.google.com"];
[webSite  setDelegate:self];
[self.view addSubview:webSite];
[webSite  release];
#pragma mark MyLabel Delegate Methods
// myLabel是你的MyLabel委托的实例, tag是该实例的tag值, 有点多余, 哈哈
- (void)myLabel:(MyLabel *)myLabel touchesWtihTag:(NSInteger)tag {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:webSite.text]];
}

转帖: http://www.cocoachina.com/bbs/read.php?tid-60903.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值