1. 程式人生 > >UITextView增加富文字AttributedString點選事件以及更改linkTextAttributes顏色

UITextView增加富文字AttributedString點選事件以及更改linkTextAttributes顏色

_tipTextView = [[UITextView alloc] init];

    _tipTextView.delegate = self;
    _tipTextView.editable = NO;        //必須禁止輸入,否則點選將彈出輸入鍵盤
    _tipTextView.scrollEnabled = NO;
    _tipTextView.backgroundColor = [UIColor clearColor];

    NSString *titleString = @"注:灰色區域只有VIP使用者可抽取";
    NSString *tapString = @"點選成為VIP";
    NSMutableAttributedString *titleAttriString = [[NSMutableAttributedString alloc] initWithString:titleString];

    NSMutableAttributedString *tapAttriString = [[NSMutableAttributedString alloc] initWithString:tapString];
    NSRange selectedRange = {0, [tapAttriString length]};


    [tapAttriString beginEditing];

// [tapAttriString addAttribute:NSUnderlineStyleAttributeName
// value:[NSNumber numberWithInt:NSSingleUnderlineStyle] // 新增下化線
// range:selectedRange];
[tapAttriString addAttribute:NSLinkAttributeName
value:@”vip://”
range:selectedRange];

// [tapAttriString setAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithSelected], NSLinkAttributeName:[NSURL URLWithString:@”vip://”] } range:selectedRange];

// [tapAttriString addAttribute:NSForegroundColorAttributeName
// value:[UIColor colorWithSelected] // 更改顏色
// range:selectedRange];

    [tapAttriString addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:15]
                            range:selectedRange];

    [titleAttriString addAttribute:NSFontAttributeName
                             value:[UIFont systemFont_13]
                             range:NSMakeRange(0, titleAttriString.length)];
    [titleAttriString addAttribute:NSForegroundColorAttributeName
                             value:[UIColor whiteColor] // 更改顏色
                             range:NSMakeRange(0, titleAttriString.length)];


    [tapAttriString endEditing];

    [titleAttriString appendAttributedString:tapAttriString];

    [_tipTextView setAttributedText:titleAttriString];
    [_tipTextView sizeToFit];

    _tipTextView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithSelected]};//設定linkTextAttributes顏色
  • (BOOL)textView:(UITextView )textView shouldInteractWithURL:(NSURL )URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@”vip”]) {
    NSLog(@”vip點選”);
    return NO;
    }
    return YES;
    }