使用子类化在NSSecureTextField中垂直居中文本

Ash*_*row 11 macos objective-c nstextfield

我正试图在我的NSTextFields中垂直居中文本,但其中一个是密码,所以它是一个NSSecureTextField.我已经将它的类设置MDVerticallyCenteredSecureTextFieldCell为以下实现:

- (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+10);
}

- (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];
}

-(void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    [super drawWithFrame:cellFrame inView:controlView];
}
Run Code Online (Sandbox Code Playgroud)

类似的子类已经适用于常规NSTextFieldCells,只是不安全的版本.似乎Apple以某种方式保护这些方法不被覆盖.

现在密码字段是唯一未对齐的字段:

未对齐的

任何人都可以建议一种NSSecureTextFieldCell方法来调用子类的方法或垂直居中文本字段的另一种方式?

小智 25

尝试使用常规NSTextField,内置NSSecureTextFieldCell子类.我有同样的问题,这种组合起作用.


sli*_*kas 5

您可以创建NSSecureTextField类似的子类:

@implementation SubclassTextField

+ (Class)cellClass {
    return [SubclassTextFieldCell class];
}

@end
Run Code Online (Sandbox Code Playgroud)

和细胞的子类:

@implementation SubclassTextFieldCell

- (NSRect)drawingRectForBounds:(NSRect)rect {
    // It will be working
    ...
}

...
@end
Run Code Online (Sandbox Code Playgroud)

如果这样做,那么子类中的方法NSSecureTextField将开始工作。

  • 这是正确的答案。在 Interface Builder 中分配自定义单元类是不够的。`-[NSSecureTextField initWithCoder:]` 检查解码的单元格的类,如果与 `+cellClass` 不匹配,将创建一个新实例。 (2认同)