1. 程式人生 > >使用YYText-文字藍色文字點選實現超連結跳轉

使用YYText-文字藍色文字點選實現超連結跳轉

    NSString *text = @"唐寅,生於成化六年二月初四,卒於嘉靖二年十二月二日,字伯虎,後改字子畏,號六如居士、桃花庵主、魯國唐生、逃禪仙吏等,明代畫家、書法家、詩人。";
    
    
    NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString: text];
    
    /**
     *  設定整段文字size
     */
//        one.yy_font = [UIFont boldSystemFontOfSize:30];
    
    /**
     *  設定整段文字下劃線
     */
//        one.yy_underlineStyle = NSUnderlineStyleSingle;
    
    /**
     *  獲得range, 只設置標記文字的size、下劃線
     */
    NSRange range = [text rangeOfString:@"字伯虎"];
    [one yy_setTextUnderline:[YYTextDecoration decorationWithStyle:YYTextLineStyleSingle] range:range];
    [one yy_setFont:[UIFont boldSystemFontOfSize:30] range:range];
    
    /**
     *  被標記的文字顏色
     */
    UIColor *textColor = [UIColor colorWithRed:0.093 green:0.492 blue:1.000 alpha:1.000];
    
    /**
     *  被標記文字點中後的背景顏色,會閃現一下
     */
//    UIColor *tapedBackgroundColor = [UIColor colorWithWhite:0.000 alpha:0.220];
    
    
    /**
     *  標記文字點選事件
     */
    [one yy_setTextHighlightRange:range color:textColor backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        // 點選就是跳轉超連結了,在這裡我輸出標記文字
        [self showMessage:[NSString stringWithFormat:@"%@, 字型大小: 30", [text.string substringWithRange:range]]];
        
    }];
    
    // 再標記一段文字
     NSRange otherRange = [text rangeOfString:@"桃花庵主"];
    [one yy_setFont:[UIFont boldSystemFontOfSize:20] range:otherRange];
    
    [one yy_setTextHighlightRange:otherRange color:[UIColor orangeColor] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        [self showMessage:[NSString stringWithFormat:@"%@, 字型大小: 20", [text.string substringWithRange:otherRange]]];

        NSLog(@"dic: %@", [text yy_fontAtIndex:otherRange.location]);
    }];