无论如何在NSAttributedString本地化时保留NSAttributedString的属性?

时间:2016-10-29 04:41:03

标签: ios objective-c localization nslocalizedstring

我试图本地化NSAttributedString。

但是,我发现NSString的属性在本地化后都消失了

无论如何保持这些属性?

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

1 个答案:

答案 0 :(得分:1)

解决方案1 ​​

创建一个方法,每次需要更新textView的内容时创建NSAttributedString

- (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