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

xiaoxiao2021-02-28  53

    

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];
转载请注明原文地址: https://www.6miu.com/read-850389.html

最新回复(0)