我从谷歌来到这里,试图对 UITextField 做同样的事情。我在下面实现了一些对 UILabel 通用的东西。
@interface AdjustableUILable : UILabel {
CGFloat characterSpacing;
}
@property CGFloat characterSpacing;
@end
@implementation AdjustableUILable
@synthesize characterSpacing;
- (void)drawTextInRect:(CGRect)rect
{
if (characterSpacing)
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat size = self.font.pointSize;
CGContextSelectFont (context, [self.font.fontName UTF8String], size, kCGEncodingMacRoman);
CGContextSetCharacterSpacing (context, characterSpacing);
CGContextSetTextDrawingMode (context, kCGTextFill);
// Rotate text to not be upside down
CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, xform);
const char *cStr = [self.text UTF8String];
CGContextShowTextAtPoint (context, rect.origin.x, rect.origin.y + size, cStr, strlen(cStr));
}
else
{
// no character spacing provided so do normal drawing
[super drawTextInRect:rect];
}
}
@end
然后要使用它,只需在 viewDidLoad 中设置标签或其他东西
- (void)viewDidLoad
{
myLabel.characterSpacing = 2; // point size
}
我用 UITextField 尝试过,但不幸的是它只在用户编辑字段后添加字符间距。-drawTextInRect 仅在 -textFieldShouldEndEditing 委托方法之后调用。来自其他论坛的一些人建议这是因为 UITextField 需要知道字体的渲染才能显示光标。从来没有为那件作品找到解决方案......