我需要在NSTextField中对齐文本,以便在动态更改字体大小(I use this to do that)时,文本的底部像素行始终保持在同一位置。
现在我有这样的场景:每当字体大小变小,例如从55到20时,文本挂在边界/框架的顶部,这不是我需要的。
我没有找到任何让我在底部but I did find this对齐文本并调整它为我的自定义NSTextFieldCell子类的东西:
- (NSRect)titleRectForBounds:(NSRect)theRect {
NSRect titleFrame = [super titleRectForBounds:theRect];
// NSSize titleSize = [[self attributedStringValue] size];
titleFrame.origin.y = theRect.origin.y;
return titleFrame;
}
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
NSRect titleRect = [self titleRectForBounds:cellFrame];
[[self attributedStringValue] drawInRect:titleRect];
}
我还使用了[myTextField setCell:myTextFieldCell];
,以便我的NSTextField使用NSTextFieldCell但没有任何改变。我没有正确调整这个或者我做错了什么吗?
您需要调整titleRect的高度,因为它比字体减少时所需的高。所以像这样调整高度并将titleRect向下移动高度差。
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
NSRect titleRect = [super titleRectForBounds:cellFrame];
NSSize titleSize = [[self attributedStringValue] size];
CGFloat heightDiff = titleRect.size.height - titleSize.height;
titleRect = NSMakeRect(titleRect.origin.x, titleRect.origin.y + heightDiff, titleRect.size.width, titleSize.height);
[[self attributedStringValue] drawInRect:titleRect];
}
您也可以使用drawAtPoint:
而不是drawInRect:
来提供精确的位置,但如果文本没有左对齐,您还必须计算正确的x位置。