iOS 最简单的可点击文本

1.遵守 UITextViewDelegate ,添加视图
@interface MyViewController ()
@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;
}

你可能感兴趣的:(iOS 最简单的可点击文本)