iOS开发 字符串中截取关键字并给他设置颜色

    


    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 300, 200)];
    contentLabel.textColor = [UIColor blackColor];
    [self.view addSubview:contentLabel];
    NSString *keyName = @"关键字";
    NSString *string = @"我是一句话,哪个字是关键字";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = NSMakeRange([[attributedString string] rangeOfString:keyName].location, keyName.length);
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    
    [contentLabel setAttributedText:attributedString];
    [contentLabel sizeToFit];

你可能感兴趣的:(iOS,开发)