我的类“TypgraphicNumberLabel”是 UILabel 的子类。此类重写了 UILabel 的“文本”setter 和 getter,目的是在表格中生成呈现良好的数字。例如,它可以添加一些额外的空白以实现右对齐、一元加号、附加单元等。
我的问题是这个类在 iOS 5.1 之前一直工作得很好,但是在 iOS 6 中,它已经停止工作:它现在完全按照标准 UILabel 进行渲染(但是当从代码访问它的属性时,它们仍然是给出正确的结果)。 由于此类在大量遗留代码中使用,我真的很想修复我的原始代码,而不是使用全新的方法重写它。因此,请将您的答案集中在解释如何在 iOS 6 中覆盖 UILabel 的“-text”和“-setText:”。
这是我的代码(简化版本):
@interface TypographicNumberLabel : UILabel {
NSString *numberText;
}
// PROPERTIES
// "text" will be used to set and retrieve the number string in its original version.
// integerValue, doubleValue, etc. will work as expected on the string.
// The property "text" is declared in UILabel, but overridden here!
// "typographicText" will be used to retrieve the string exactly as it is rendered in the view.
// integerValue, doubleValue, etc. WILL NOT WORK on this string.
@property (nonatomic, readonly) NSString* typographicText;
@end
@implementation TypographicNumberLabel
- (void) renderTypographicText
{
NSString *renderedString = nil;
if (numberText)
{
// Simplified example!
// (Actual code is much longer.)
NSString *fillCharacter = @"\u2007"; // = "Figure space" character
renderedString = [fillCharacter stringByAppendingString: numberText];
}
// Save the typographic version of the string in the "text" property of the superclass (UILabel)
// (Can be retreived by the user through the "typographicText" property.)
super.text = renderedString;
}
#pragma mark - Overridden UILabel accessor methods
- (NSString *) text
{
return numberText;
}
- (void) setText:(NSString *) newText
{
if (numberText != newText)
{
NSString *oldText = numberText;
numberText = [newText copy];
[oldText release];
}
[self renderTypographicText];
}
#pragma mark - TypographicNumberLabel accessor methods
- (NSString *) typographicText
{
return super.text;
}
@end
使用示例(aLabel从.xib文件加载):
@property(nonatomic, retain) IBOutlet TypographicNumberLabel *aLabel;
self.aLabel.text = @"12";
int interpretedNumber = [self.aLabel.text intValue];
这种类型的代码在 iOS 5.1 和 iOS 6 中都工作得很好,但在 iOS 6 中屏幕上的渲染是错误的!在那里,TypographicNumberLabel 的工作方式就像 UILabel 一样。不会添加“图形空间”字符。
最佳答案
问题位于
- (NSString *) text
{
return numberText;
}
可以看到方法([self text])是内部调用的,所以最好返回你想要显示的文本,否则很容易破坏内部控制逻辑:
- (NSString *) text
{
return [super text];
}
关于ios - 在 UILabel 中覆盖 "text"在 iOS 6 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14258345/