私のクラス「TypographicNumberLabel」は、UILabel のサブクラスです。このクラスは、UILabel の「テキスト」セッターとゲッターをオーバーライドして、テーブルに適切にレンダリングされた数値を生成します。たとえば、右揃え、単項プラス記号、単位の追加などのために余分な空白を追加できます。
私の問題は、このクラスが 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 と同じように機能します。「フィギュアスペース」キャラクターは追加されません。