更新时间:2022-11-02 12:17:45
您可以将NSTextFieldCell
子类化以完成您想要做的事情:
You could subclass NSTextFieldCell
to do what you want:
MDVerticallyCenteredTextFieldCell.h:
MDVerticallyCenteredTextFieldCell.h:
#import <Cocoa/Cocoa.h>
@interface MDVerticallyCenteredTextFieldCell : NSTextFieldCell {
}
@end
MDVerticallyCenteredTextFieldCell.m:
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
(或您要为其命名的任何名称)作为文本字段的文本字段单元格的自定义类(选择文本字段,暂停,然后单击再次在文本字段中选择文本字段内的单元格):
You can then use a regular NSTextField
in Interface Builder, and specify MDVerticallyCenteredTextFieldCell
(or whatever you want to name it) as the custom class for the text field's text field cell (select the textfield, pause, then click the textfield again to select the cell inside the text field):