同NSTextField一样,NSSecureTextField有一个NSSecureTextFieldCell,因此实现NSSecureTextField内容的垂直居中,可以从NSSecureTextFieldCell下手。
代码:
//
// VerticalSecureTextFieldCell.h
//
// Created by liyuye.
//
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
@interface VerticalSecureTextFieldCell : NSSecureTextFieldCell
@end
NS_ASSUME_NONNULL_END
//
// VerticalSecureTextFieldCell.m
//
// Created by liyuye.
//
#import "VerticalSecureTextFieldCell.h"
@implementation VerticalSecureTextFieldCell
- (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;
}
-