iOS 最简单的可点击文本

1.遵守 UITextViewDelegate ,添加视图

@interface MyViewController ()<UITextViewDelegate>
@property(nonatomic,strong)UITextView * protocol;
@end

@implementation YNP_SpreadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.protocol];
}

-(UITextView *)protocol{
    if (!_protocol) {
        _protocol = [[UITextView alloc] initWithFrame:CGRectMake(0, 100, 375, 50)];
        _protocol.backgroundColor = [UIColor clearColor];
        _protocol.editable = NO;
        _protocol.delegate = self;
        _protocol.attributedText = [self.viewModel createProtocolText];
    }
    return _protocol;
}

@end
复制代码

2.创建可以点击的富文本,设置可点击的关键字为“click

-(NSMutableAttributedString *)createProtocolText{
    //普通字体的大小颜色
    NSDictionary * normalAtt = @{NSFontAttributeName:[UIFont systemFontOfSize:13], NSForegroundColorAttributeName:[UIColor colorFromHexValue:0x999999]};
   
    //可点击字体的大小颜色
    NSDictionary * specAtt = @{NSFontAttributeName:[UIFont systemFontOfSize:13], NSForegroundColorAttributeName:[UIColor colorFromHexValue:0x27a1ff]};
    
    //生成默认的字符串
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc] initWithString:@"已阅读并同意" attributes:normalAtt];
    
    //添加特殊部分在尾部
    NSMutableAttributedString * click = [[NSMutableAttributedString alloc] initWithString:@"《服务协议》" attributes:specAtt];
    [attStr appendAttributedString:click];
    
    //设置居中
    NSMutableParagraphStyle * style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentCenter;
    [attStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, attStr.length)];
    
    //添加点击事件
    NSString * value = [NSString stringWithFormat:@"click://"];
    [attStr addAttribute:NSLinkAttributeName value:value range:[[attStr string] rangeOfString:[click string]]];
    
    return attStr;
}
复制代码

3.实现textview的代理方法,通过 URL.sheme 识别点击的部分

在这个代理方法这里可以添加自己需要的操作

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([URL.scheme isEqualToString:@"click"]) {
        NSLog(@"text click");
        return NO;
    }
    return YES;
}
复制代码

end with command + R

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值