2016-10-29 70 views
1

我想本地化一個NSAttributedString。有沒有辦法在本地化時保留NSAttributedString的屬性?

但是,我發現NSString的屬性全都在本地化後失效

反正有保留那些屬性?

self.doctorUITextView.attributedText = NSLocalizedString([doctorNSMutableAttributedString string], nil); 
+0

您發佈的代碼甚至不會編譯。請在你的問題中發佈有效的代碼。你不能指定一個'NSString'到期望'NSAttributedString'的屬性。 – rmaddy

+0

@rmaddy這實際上是問題所在。 NSString的屬性都在本地化之後,因爲它只能返回一個NSString,但我需要一個NSAttributedString作爲屬性文本。 –

回答

1

解決方案1 ​​

創建它創建NSAttributedString每次你需要更新textView的內容

- (void) setDoctorText: (NSString *) string { 
    //create your attributes dict 
    UIFont *keyFont = [UIFont fontWithName:@"Courier" size:16]; 
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:keyFont forKey:NSFontAttributeName]; 

    _doctorTextView.attributedText = [[NSAttributedString alloc] initWithString:string attributes:attributes]; 
} 

使用時間的方法:

[self setDoctorText:NSLocalizedString(@"your string", @"")]; 

,而不是這個:

_doctorTextView.attributedText = @"your string"; 

解決方案2:

也許不是最完美的解決方案,但您可以創建NSMutableAttributedString屬性,並設置它在viewDidLoad屬性一次。然後,無論何時需要更新textView的文本,只需通過存儲的可變屬性文本即可完成。

@interface ViewController() 

@property (weak, nonatomic) IBOutlet UITextView *doctorTextView; 
@property (nonatomic, strong) NSMutableAttributedString *doctorAttributedString; 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    UIFont *keyFont = [UIFont fontWithName:@"Courier" size:16]; 
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:keyFont forKey:NSFontAttributeName]; 
    _doctorAttributedString = [[NSMutableAttributedString alloc] initWithString:@" " attributes:attributes]; 
} 

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 

    _doctorAttributedString.mutableString.string = NSLocalizedString(@"your string", @""); 
    _doctorTextView.attributedText = _doctorAttributedString; 
} 

@end 
相關問題