如何在NSTextField中垂直居中对齐文本?

时间:2011-12-24 13:30:25

标签: objective-c xcode macos

我有一个NSTextField,我想垂直居中对齐文本。基本上我需要How do I vertically center UITextField Text?

的NSTextField答案

有人有指点吗?谢谢!

3 个答案:

答案 0 :(得分:18)

您可以将NSTextFieldCell子类化为您想做的事情:

MDVerticallyCenteredTextFieldCell.h:

#import <Cocoa/Cocoa.h>

@interface MDVerticallyCenteredTextFieldCell : NSTextFieldCell {

}

@end

MDVerticallyCenteredTextFieldCell.m:

#import "MDVerticallyCenteredTextFieldCell.h"

@implementation MDVerticallyCenteredTextFieldCell

- (NSRect)adjustedFrameToVerticallyCenterText:(NSRect)frame {
    // super would normally draw text at the top of the cell
    NSInteger offset = floor((NSHeight(frame) - 
           ([[self font] ascender] - [[self font] descender])) / 2);
    return NSInsetRect(frame, 0.0, offset);
}

- (void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView
         editor:(NSText *)editor delegate:(id)delegate event:(NSEvent *)event {
    [super editWithFrame:[self adjustedFrameToVerticallyCenterText:aRect]
          inView:controlView editor:editor delegate:delegate event:event];
}

- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView
                 editor:(NSText *)editor delegate:(id)delegate 
                  start:(NSInteger)start length:(NSInteger)length {

    [super selectWithFrame:[self adjustedFrameToVerticallyCenterText:aRect]
                    inView:controlView editor:editor delegate:delegate
                     start:start length:length];
}

- (void)drawInteriorWithFrame:(NSRect)frame inView:(NSView *)view {
    [super drawInteriorWithFrame:
       [self adjustedFrameToVerticallyCenterText:frame] inView:view];
}

@end

然后,您可以在Interface Builder中使用常规NSTextField,并将MDVerticallyCenteredTextFieldCell(或任何您想要命名的内容)指定为文本字段的文本字段单元格的自定义类(选择文本字段,暂停,然后再次单击文本字段以选择文本字段内的单元格:

enter image description here

答案 1 :(得分:4)

Swift 3.0版本(为NSTextFieldCell创建自定义子类):

override func drawingRect(forBounds rect: NSRect) -> NSRect {
    var newRect = super.drawingRect(forBounds: rect)
    let textSize = self.cellSize(forBounds: rect)
    let heightDelta = newRect.size.height - textSize.height
    if heightDelta > 0 {
        newRect.size.height -= heightDelta
        newRect.origin.y += (heightDelta / 2)
    }
    return newRect
}

答案 2 :(得分:2)

在计算可能的最大字体高度时,最好使用boundingRectForFont和函数ceilf(),因为上述解决方案会导致文本在基线下被切断。所以adjustedFrameToVerticallyCenterText:看起来像这样

- (NSRect)adjustedFrameToVerticallyCenterText:(NSRect)rect {
    CGFloat fontSize = self.font.boundingRectForFont.size.height;
    NSInteger offset = floor((NSHeight(rect) - ceilf(fontSize))/2);
    NSRect centeredRect = NSInsetRect(rect, 0, offset);
    return centeredRect;
}