1. 程式人生 > >UILabel文字可點選

UILabel文字可點選

 TTTAttributedLabel 庫地址 https://github.com/TTTAttributedLabel/TTTAttributedLabel

#import "ViewController.h"

@interfaceViewController () <TTTAttributedLabelDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {

    [superviewDidLoad];

TTTAttributedLabel *label = [[TTTAttributedLabelalloc

initWithFrame:CGRectMake(10012012060)];

    label.font = [UIFontsystemFontOfSize:14];

    label.textColor = [UIColorblackColor];

    label.lineBreakMode = NSLineBreakByCharWrapping;

    label.numberOfLines = 0;

//設定高亮顏色

    label.highlightedTextColor = [UIColorgreenColor];

//檢測url

    label.enabledTextCheckingTypes = 

NSTextCheckingTypeLink;

//對齊方式

    label.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;

//行間距

    label.lineSpacing = 8;

//設定陰影

    label.shadowColor = [UIColorgrayColor];

    label.delegate = self// Delegate

//NO 不顯示下劃線

    label.linkAttributes = [NSDictionarydictionaryWithObject:[

NSNumbernumberWithBool:NOforKey:(NSString *)kCTUnderlineStyleAttributeName];

NSString *text = @"冷清風 讚了 王戰 的說說";

    [label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString*mutableAttributedString)

    {

//設定可點選文字的範圍

NSRange boldRange = [[mutableAttributedString stringrangeOfString:@"冷清風"options:NSCaseInsensitiveSearch];

//設定可點選文字的的大小

        UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:16];

CTFontRef font = CTFontCreateWithName((__bridgeCFStringRef)boldSystemFont.fontName, boldSystemFont.pointSizeNULL);

        if (font) {

            //設定可點選文字的大小

            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange];

            //設定可點選文字的顏色

            [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeNamevalue:(id)[[UIColorblueColorCGColorrange:boldRange];

            CFRelease(font);

        }

       return mutableAttributedString;

    }];

    //正則

NSRegularExpression *regexp = NameRegularExpression();

NSRange linkRange = [regexp rangeOfFirstMatchInString:text options:0range:NSMakeRange(03)];

NSURL *url = [NSURLURLWithString:[NSStringstringWithFormat:@"http://www.exiucai.com/"]];

//設定連結的url

    [label addLinkToURL:url withRange:linkRange];

    [self.view addSubview:label];

}

- (void)attributedLabel:(__unused TTTAttributedLabel *)label

   didSelectLinkWithURL:(NSURL *)url

{

  NSLog(@"click點選");

}