iOS 之富文本可点击

来源:互联网 发布:大战神武将升阶数据 编辑:程序博客网 时间:2024/04/30 03:52

相信大家很多都遇到过这种情况,尤其是在登录注册界面,需要同意一个什么什么协议才能继续往下进行。而这个协议的文字是一个字符串,但是内容的颜色不同,有时候内容的字体大小也不同,而且最最重要的一点是这个字符串的一部分是可以响应事件的。

是不是?肯定不少人都遇到过这种情况。

其实,苹果公司早在ios6的时候,就有了相应的方案。。。。

算了,不啰嗦了,直接上代码吧!

1.初始化:

写了一个继承自UIView 的类,

- (instancetype)initWithFrame:(CGRect)frame{    if (self = [super initWithFrame:frame]) {        _textView = [[UITextView alloc]initWithFrame:self.bounds];        _textView.delegate = self;        _textView.editable = NO;//必须禁止输入,否则点击将会弹出输入键盘        _textView.scrollEnabled = NO;//可选的,视具体情况而定        [self addSubview:_textView];    }    return self;}

2.赋值

声明一个属性content 为了传递文本内容,重写它的setter方法:

- (void)setContent:(NSString *)content {    _content = content;    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:content];    [attStr addAttribute:NSLinkAttributeName value:@"click://" range:NSMakeRange(6, 9)];    [attStr addAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:20]} range:NSMakeRange(6, 9)];    _textView.attributedText = attStr;}

将值赋给了textView

3.实现协议:

要想让这段文本可点击,需要实现UITextView的一个协议方法:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{    if ([[URL scheme] isEqualToString:@"click"]) {        NSAttributedString *abStr = [textView.attributedText attributedSubstringFromRange:characterRange];        if (self.eventBlock) {            self.eventBlock(abStr);        }        return NO;    }    return YES;}

这里我写了一个block将点击的部分对应的文字信息传出去。

4.调用

最后,在controller中调用:

 AttributeTouchLabel*label = [[AttributeTouchLabel alloc]initWithFrame:CGRectMake(10, 100, 300, 60)];    label.content = @"您将同意《 巴拉巴拉小魔仙协议 》";    [label returnWithBlock:^(NSAttributedString *abStr) {        NSLog(@"%@",abStr);    }];    [self.view addSubview:label];

附上效果图:

这里写图片描述

这里的蓝色部分是可以响应事件的!点击后打印的结果:

2017-03-23 16:27:41.749 AttributedStringClick[29792:1371671] 巴拉巴拉小魔仙协议{    NSColor = "UIExtendedSRGBColorSpace 1 0.5 0 1";    NSFont = "<UICTFont: 0x7fc34fd0ee10> font-family: \".PingFangSC-Regular\"; font-weight: normal; font-style: normal; font-size: 20.00pt";    NSLink = "click://";    NSOriginalFont = "<UICTFont: 0x7fc34fe07cc0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt";}
0 0
原创粉丝点击