2016-10-26 5 views
0
UIFont *keyFont = [UIFont fontWithName:@"Roboto-bold" size:16]; 
NSDictionary *keyFontDict = [NSDictionary dictionaryWithObject:keyFont forKey:NSFontAttributeName]; 
NSMutableAttributedString *titleAttrStr = [[NSMutableAttributedString alloc] initWithString:@"" attributes:keyFontDict]; 

NSString *str = @"ABC"; 
[titleAttrStr.mutableString setString:str]; 

上記の属性文字列を設定すると、フォントが適用されません。 私は以下のフォーマットでフォントを取得できます。NSMutableAttributedString文字列をリセットするとその属性が適用されませんか?

NSMutableAttributedString *titleAttrStr = [[NSMutableAttributedString alloc] initWithString:str attributes:keyFontDict]; 

私は一度だけ&文字列をresetingによってAttributedStringのを使用を作成します。あなたがオブジェクトを作成するときには、現時点では非空の文字列を使用している場合

+0

'replaceCharactersInRange:withString:'を使用しますか? – Larme

+0

'EMPTY_STR 'とは何ですか? –

+0

その空の文字列が更新されました – balusu

答えて

0

、それが期待どおりに動作します:

NSMutableAttributedString *titleAttrStr = [[NSMutableAttributedString alloc] initWithString:@" " attributes:keyFontDict]; 
-1

私のコードはあなたに

NSString *strLocation = [NSString stringWithFormat:@"%@%@", @"ABC",@"DEF"]; 
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:strLocation]; 
[attributedText addAttribute:NSFontAttributeName value:[UIFont fontWithName : @"Roboto-Bold" size : 16] range:NSMakeRange(0, [strLocation length])]; 
attributedText = [self addFont:attributedText toText:@"ABC"]; 
lblQue.attributedText = attributedText; 

- (NSMutableAttributedString *)addFont:(NSMutableAttributedString *)attributedString toText:(NSString *)subString { 
    NSRange substriingRange = [[attributedString string] rangeOfString:subString]; 
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:substriingRange]; //TextColor 
    [attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName : @"Roboto-Bold" size : 16] range:substriingRange]; //TextFont 
    return attributedString; 
} 
0

しまうのに役立ちます。このコードを使用してくださいファクトリ関数や何らかのテキストを含む文字列を構築するための何かを持っている方が良いのではないでしょうか?

- (NSAttributedString *)attributedTextWithString:(NSString *) string { 
    UIFont *keyFont = [UIFont fontWithName:@"Roboto-bold" size:16]; 
    // make sure to use modern Objective-C syntax too... 
    NSDictionary *keyFontDict = @{NSFontAttributeName: keyFont}; 
    return [[NSMutableAttributedString alloc] initWithString:string attributes:keyFontDict]; 
} 

文字列の作成は、新しい文字列値でその関数を呼び出す場合に過ぎません。

実際に属性付き文字列を作成する場所は1つだけです(変更する必要がある場合など)。

属性付き文字列の作成は、一度作成して更新するだけで十分です。毎回新しいものから作成してください。

0

古い文字列をリセットして属性を再適用することができます。これはまだ高価ですが、少なくともNSAttributedStringを再割り当てする必要はありません。

[titleAttrStr replaceCharactersInRange:NSRangeFromString(titleAttrStr.string) withString:@"someNewStrig"]; 
[titleAttrStr setAttributes:keyFontDict range:NSRangeFromString(titleAttrStr.string)]; 
関連する問題