0

I am trying to retroactively localize an app by subclassing an IBDesignable to have a property like so:

@property IBInspectable NSString *localizedKey;

Then I thought I could easily override the proper function in the UILabel's lifecycle to do this:

if (self.localizedKey) self.text = NSLocalizedString(self.localizedKey, nil);

Here's an example of what I tried to do:

- (void) drawRect:(CGRect)rect {
    NSLog(@"roundedlabel");
    [super drawRect:rect];
    [self.layer setCornerRadius:cornerRadius];
    [self.layer setMasksToBounds:YES];
    [self.layer setBorderWidth:borderWidth];
    [self.layer setBorderColor:[borderColor CGColor]];
    self.clipsToBounds = YES;
}

- (void) willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];
    NSLog(@"roundedlabel");
    if (self.localizedKey) self.text = NSLocalizedString(self.localizedKey, nil);
}

I also tried moving the if (self.localizedKey) to various locations in drawRect.

My plan was to then set up the Localizable.strings file manually with known localizedKeys assigned working through the XIB files. However, I am finding two things.

  1. It seems as though the normal methods called in the life cycle of a view are not being called for my IBDesignable UILabel subclass. I have entered log statements into drawRect and willMoveToSuperview, and these log statements never print out.
  2. XCode almost always crashes & immediately closes when I try to open a xib in Interface Builder that contains this subclassed label (so no error messages).

At run time, when I see a view that involves an affected xib, I don't see any sign of the localized string AND I don't see 'roundedlabel' printed anywhere in my log.

What's going on? In particular:

(1) How come these functions don't run at all for my subclassed IBDesignable UILabel subclass? (2) Is there a way to do what I want to do?

4

1 に答える 1

0

拡張機能を作成UILabelし、ストーリーボード/XIB でランタイム キー値を使用して、ローカリゼーション キーを設定します。

extension UILabel {
    func setHBLocalisationKey(key: String) {
        self.text = ...
     }
}

また

@implementation UILabel (HBLocalisation)

    - (void)setHBLocalisationKey:(NSString *)key {
        self.text = NSLocalizedString(key, nil);
    }

@end

これは、カスタム サブクラスを必要とせずに任意のラベルで機能するようになり、現在のアプローチでいくつかの問題を引き起こしていると思われる Xcode UI を改ざんしません。

于 2016-04-06T06:38:09.473 に答える