2011-12-24 160 views

回答

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(或任何你想命名它)作为文本f的自定义类ield的文本字段单元格(选中文本框,暂停,然后再次单击文本框,选择文本字段中的单元格):

enter image description here

+0

这是伟大的,除了它导致文本溢出左侧和右侧的文本框架框外。有任何想法吗? – 2011-12-25 02:38:34

+0

@ simon.d:你是......嗯。我一直在使用这段代码(我相信它是从我在某处找到的一些苹果示例代码改编而来)一段时间没有问题,但我现在意识到它只用单行(非包装)'NSTextField's。我会再看看它,看看我是否无法在多行文本字段中工作...... – NSGod 2011-12-25 20:54:59

+0

editWithFrame不会被调用 – 2016-09-16 16:23:50

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; 
} 
1

雨燕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 
}