NSTextField里面有一个NSTextFieldCell,因此NSTextField实现内容垂直居中,主要是实现NSTextFieldCell内容的居中。代码如下:
//
// VerticalTextFieldCell.h
//
// Created by liyuye.
//
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
@interface VerticalTextFieldCell : NSTextFieldCell
@end
NS_ASSUME_NONNULL_END
//
// VerticalTextFieldCell.m
//
// Created by liyuye.
//
#import "VerticalTextFieldCell.h"
@implementation VerticalTextFieldCell
- (NSRect)adjustedFrameToVerticallyCenterText:(NSRect)frame {
// super would normally draw text at the top of the cell
CGFloat fontSize = self.font.boundingRectForFont.size.height;
NSInteger offset = floor((NSHeight(frame) - ceilf(fontSize))/2);
NSRect centeredRect = NSInsetRect(frame, 2, offset);
return centeredRect;
}
- (NSRect)drawingRectForBounds:(NSRect)rect{
NSRect newRect = [super drawingR