の 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];
}];
}
問題が 1 つあります。TextFormattingElement
範囲が交差する 2 つのインスタンスがある場合 (例:NSMakeRange(9,28)
とNSMakeRange(26,7)
)、下線の太さは常に最後の要素のフォント サイズに依存する値になります。この図は、このスクリーンショットで見ることができます:
私の2つのフォーマット要素のパラメータは次のとおりです。
1 つ目: 位置 = 9、長さ = 28、fontName = TimesNewRomanPSMT、fontSize = 15、fontColor = UIDeviceRGBColorSpace 1 0 0 1、isBold = 0、isItalic = 0、isUnderlined = 1、isStriked = 0
2番目: 位置 = 26、長さ = 7、fontName = TimesNewRomanPSMT、fontSize = 25、fontColor = UIDeviceRGBColorSpace 0 0 1 1、isBold = 1、isItalic = 0、isUnderlined = 1、isStriked = 0
しかし、Google ドキュメントのような効果を得たい:
TextKit を使用してこれを行うにはどうすればよいですか?