iOS 一段文字中颜色不同且可点击

2020-12-03  本文已影响0人  余鹤龄

- (UITextView *)ReconnectionDesTextView

{

    if (!_ReconnectionDesTextView) {

        _ReconnectionDesTextView = [UITextView new];

        _ReconnectionDesTextView.editable = NO;

        _ReconnectionDesTextView.delegate = self;

        _ReconnectionDesTextView.font = Font(12);

        _ReconnectionDesTextView.scrollEnabled = NO;

        _ReconnectionDesTextView.textColor = [UIColor yellowColor];

        _ReconnectionDesTextView.backgroundColor = [UIColor clearColor];

        NSString *str1 = @"如果你的设备因损坏、丢失或其他原因无法连接次应用,请点击此处";

        NSString*str2 =@"解绑设备。";

        NSString*str = [NSStringstringWithFormat:@"%@%@",str1,str2];

        NSRangerange1 = [strrangeOfString:str1];

        NSRangerange2 = [strrangeOfString:str2];

        NSMutableAttributedString *mastring = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12.0f]}];

        [mastringaddAttribute:NSForegroundColorAttributeName value:Main5B5B5B range:range1];

        [mastringaddAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range2];

        // 2.要有后面的方法,如果含有中文,url会无效,所以转码

        NSString *valueString1 = [[NSString stringWithFormat:@"content://%@",str2] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

        [mastringaddAttribute:NSLinkAttributeNamevalue:valueString1range:range2];

        _ReconnectionDesTextView.attributedText = mastring;

        _ReconnectionDesTextView.textAlignment = NSTextAlignmentCenter;

//        _ReconnectionDesTextView.linkTextAttributes = @{NSForegroundColorAttributeName: [ColorManager setTextColor],

//                                          NSUnderlineColorAttributeName: [UIColor lightGrayColor],

//                                          NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

    }

    return _ReconnectionDesTextView;

}

#pragma mark - UITextViewDelegate ----核心代码

- (BOOL)textView:(UITextView*)textViewshouldInteractWithURL:(NSURL*)URLinRange:(NSRange)characterRange {

    if ([[URL scheme] isEqualToString:@"content"]) {

        //《隐私政策》

        NSLog(@"点击");

        returnNO;

    }

    return YES;

}

上一篇 下一篇

猜你喜欢

热点阅读