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 回答