Bạn có thể phân lớp NSTextFieldCell
để làm những gì bạn muốn:
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
Sau đó, bạn có thể sử dụng thường xuyên NSTextField
trong Interface Builder và chỉ định MDVerticallyCenteredTextFieldCell
(hoặc bất kỳ thứ gì bạn muốn đặt tên) làm lớp tùy chỉnh cho văn bản f tế bào trường văn bản ield của (chọn textfield, tạm dừng, sau đó nhấp vào textfield lần nữa để chọn các tế bào bên trong lĩnh vực văn bản):
kiểm tra câu trả lời này quá: http://stackoverflow.com/a/39945456/73195 – Hejazi