【问题标题】:NSTextField bottom-alignedNSTextField 底部对齐
【发布时间】:2012-07-02 22:33:38
【问题描述】:

我需要将 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 但没有任何改变。我没有正确调整这个还是我做错了什么?

【问题讨论】:

    标签: objective-c vertical-alignment nstextfield nstextfieldcell


    【解决方案1】:

    您需要调整 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 位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-03
      • 2020-07-16
      • 1970-01-01
      • 2017-02-16
      • 2017-06-25
      • 2012-04-29
      • 2020-12-28
      • 2012-11-06
      相关资源
      最近更新 更多