我正在使用 textStorage 的属性UITextView
。我有字符串和我的类的对象数组TextFormattingElement
。此类的一个实例由NSRange
(必须在文本中应用此元素)和一些格式参数组成:
@interface TextFormattingElement : NSObject
@property (nonatomic) NSRange range;
@property (nonatomic, strong) NSString *fontName; //e.g. @"TimesNewRomanPSMT"
@property (nonatomic) int fontSize;
@property (nonatomic, strong) UIColor *fontColor;
@property (nonatomic) BOOL isBold;
@property (nonatomic) BOOL isItalic;
@property (nonatomic) BOOL isUnderlined;
@property (nonatomic) BOOL isStriked;
@end
现在我遍历这个数组并将这些元素依次应用到 textView 的 textStorage 中。我使用这种方法:
-(void)setFontWithName:(NSString*)name AndSize:(float)fontSize AndTextColor:(UIColor*)textColor AndIsBold:(BOOL)isBold AndIsItalic:(BOOL)isItalic AndIsUnderlined:(BOOL)isUnderLined andIsStriked:(BOOL)isStriked ToRange:(NSRange)rangeToSet{
__block UIFont *font = [UIFont fontWithName:name size:fontSize];
__block UIFontDescriptor *fontDescriptor = [font fontDescriptor];
[textView.textStorage enumerateAttributesInRange:rangeToSet options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
NSParagraphStyle *paragraphStyle = [attrs objectForKey:NSParagraphStyleAttributeName];
NSMutableDictionary *attributesToSetDict = [NSMutableDictionary dictionary];
[attributesToSetDict setObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; //i need to clear all attributes at this range exсept NSParagraphStyleAttributeName
if(isBold){
uint32_t existingTraitsWithNewTrait = [fontDescriptor symbolicTraits] | UIFontDescriptorTraitBold;
fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];
}
if(isItalic){
uint32_t existingTraitsWithNewTrait = [fontDescriptor symbolicTraits] | UIFontDescriptorTraitItalic;
fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];
}
font = [UIFont fontWithDescriptor:fontDescriptor size:fontSize];
[attributesToSetDict setObject:font forKey:NSFontAttributeName];
[attributesToSetDict setObject:textColor forKey:NSForegroundColorAttributeName];
if(isUnderLined){
[attributesToSetDict setObject:@1 forKey:NSUnderlineStyleAttributeName];
}
if(isStriked){
//TODO: isStriked
}
[textView.textStorage setAttributes:attributesToSetDict range:range];
}];
}
我有一个问题:如果我有两个TextFormattingElement
具有交叉范围的实例(例如NSMakeRange(9,28)
和NSMakeRange(26,7)
),则下划线的粗细总是取决于最后一个元素的字体大小。您可以在此屏幕截图中看到此说明:
我的 2 个格式化元素的参数是:
第一个:位置 = 9,长度 = 28,fontName = TimesNewRomanPSMT,fontSize = 15,fontColor = UIDeviceRGBColorSpace 1 0 0 1,isBold = 0,isItalic = 0,isUnderlined = 1,isStriked = 0
第二:位置 = 26,长度 = 7,fontName = TimesNewRomanPSMT,fontSize = 25,fontColor = UIDeviceRGBColorSpace 0 0 1 1,isBold = 1,isItalic = 0,isUnderlined = 1,isStriked = 0
但我想获得类似 Google Docs 的效果:
如何使用 TextKit 做到这一点?