iOS 实用的简单富文本--UITextView实现

2023-03-07  本文已影响0人  人间四月天_Andy

实用的简单富文本--UITextView实现,仅供参考,欢迎学习交流。

在登录页,经常看到这样的字眼“xxx即表示同意AAAA和BBBB”,这里记录一下简单的实现方式,仅供参考。


直接上代码

当然需要先遵守UITextView的协议: <UITextViewDelegate>

@property (nonatomic, strong) UITextView *userProtocolAndPrivacyTextView;
[self.view addSubview:self.userProtocolAndPrivacyTextView];
- (UITextView *)userProtocolAndPrivacyTextView {
    if (!_userProtocolAndPrivacyTextView) {
        _userProtocolAndPrivacyTextView = [[UITextView alloc] initWithFrame:CGRectMake(24, 100, [UIScreen mainScreen].bounds.size.width - 48, 30)];
        _userProtocolAndPrivacyTextView.backgroundColor = [UIColor clearColor];
//        _userProtocolAndPrivacyTextView.font = [UIFont regularPingFangFontOfSize:14];
//        _userProtocolAndPrivacyTextView.textColor = [UIColor colorWithRed:165/255.0 green:165/255.0 blue:165/255.0 alpha:1.0];
        _userProtocolAndPrivacyTextView.editable = NO;
        
        _userProtocolAndPrivacyTextView.delegate = self;
        
        _userProtocolAndPrivacyTextView.textContainer.lineFragmentPadding = 0.0;
        
        _userProtocolAndPrivacyTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
        _userProtocolAndPrivacyTextView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRed:35/255.0 green:135/255.0 blue:230/255.0 alpha:1.0]};
        NSString *preTips = [NSString stringWithFormat:@"xx即表示同意"];
        NSString *userProtocol= [NSString stringWithFormat:@"AAAA"];
        NSString *privacyPolicy = [NSString stringWithFormat:@"BBBB"];

        NSString *string = [NSString stringWithFormat:@"%@%@和%@", preTips, userProtocol, privacyPolicy];
        NSMutableAttributedString *privacy = [[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:[UIColor colorWithRed:165/255.0 green:165/255.0 blue:165/255.0 alpha:1.0]}];
        
        NSRange userProtocolRange = [string rangeOfString:userProtocol];
        NSRange privacyPolicyRange = [string rangeOfString:privacyPolicy];
        
        [privacy addAttribute:NSLinkAttributeName value:@"user://" range:userProtocolRange];
        
        [privacy addAttribute:NSLinkAttributeName value:@"privacy://" range:privacyPolicyRange];

        _userProtocolAndPrivacyTextView.attributedText = privacy;
    }
    return _userProtocolAndPrivacyTextView;
}

接下来,看效果图:


效果图.png

点击对应的蓝色文字就会触发UITextView的代理方法,如下:

//MARK: -- UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(nonnull NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction  API_AVAILABLE(ios(10.0)) {
    if ([URL.scheme isEqualToString:@"user"]) {
        NSLog(@"AAAA");
    } else if ([URL.scheme isEqualToString:@"privacy"]) {
        NSLog(@"BBBB");
    }
    return YES;
}

参考链接:https://blog.csdn.net/ForeverMyheart/article/details/117411351

上一篇下一篇

猜你喜欢

热点阅读