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

sim*_*n.d 11 macos xcode objective-c

我有一个NSTextField,我想垂直居中对齐文本.基本上我需要NSTextField答案如何垂直居中UITextField文本?

有人有指点吗?谢谢!

NSG*_*God 18

您可以子类化NSTextFieldCell以执行您想要的操作:

MDVerticallyCenteredTextFieldCell.h:

#import <Cocoa/Cocoa.h>

@interface MDVerticallyCenteredTextFieldCell : NSTextFieldCell {

}

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述


Ben*_*o85 5

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
}
Run Code Online (Sandbox Code Playgroud)