(都写在一篇博客上面,发现下部分直接没有了,只能写个下篇了)
// 修改高亮时字体颜色
[textView.markedTextStyle setValue:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
[textView.markedTextStyle setValue:[UIColor blackColor] forKey:NSBackgroundColorAttributeName];
[textView.markedTextStyle setValue:[UIFont systemFontOfSize:20.0] forKey:NSFontAttributeName];
NSDictionary *dict = @{
NSForegroundColorAttributeName:[UIColor blackColor],
NSBackgroundColorAttributeName:[UIColor blackColor],
NSFontAttributeName:[UIFont systemFontOfSize:20.0]
};
[textView setMarkedTextStyle:dict];
+ (UIImage *)makeTextToImage:(NSString *)text font:(CGFloat)fontSize {
UIFont *font = [UIFont systemFontOfSize:fontSize];
CGFloat height = font.lineHeight;
NSDictionary *attrDict = @{
NSFontAttributeName:font,
NSForegroundColorAttributeName:kXZMainBgColor,
NSBackgroundColorAttributeName:[UIColor greenColor]
};
CGSize stringSize = [text sizeWithAttributes:attrDict];
UIGraphicsBeginImageContextWithOptions(stringSize, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetCharacterSpacing(ctx, 10);
CGContextSetTextDrawingMode (ctx, kCGTextFillStroke);
CGContextSetRGBFillColor (ctx, 0.1, 0.2, 0.3, 1); // 6
CGContextSetRGBStrokeColor (ctx, 0, 0, 0, 1);
CGRect rect = CGRectMake(0, 0, stringSize.width , height);
[text drawInRect:rect withAttributes:attrDict];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
+ (void)xz_makeWordsAnotherColor:(NSString *)attributeText color:(UIColor *)color view:(UITextView *)textView {
// 获取当前 textView 属性文本 => 可变的
NSMutableAttributedString *attrStrM = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
// 创建属性文本
XZTextAttachment *attachment = [[XZTextAttachment alloc] init];
attachment.image = [self makeTextToImage:attributeText font: 13.0];
attachment.chs = attributeText;
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithAttributedString: [NSAttributedString attributedStringWithAttachment:attachment]];
// 记录光标位置
NSRange range = textView.selectedRange;
// 将属性文本插入到当前的光标位置
[attrStrM replaceCharactersInRange:range withAttributedString:attrStr];
// 设置文本
textView.attributedText = attrStrM;
// 恢复光标位置
NSRange rangeNow = NSMakeRange(range.location + 1, 0);
textView.selectedRange = rangeNow;
}
实现效果如下:
XZ_iOS之UITextView或UITextField实时修改输入的部分文字的颜色(上)
附代码地址,欢迎Star:https://github.com/CoderXAndZ/XZTextView2
1638




被折叠的 条评论
为什么被折叠?



