如何在NSTextField中垂直居中对齐文本? [英] How do I vertically center align text in a NSTextField?

查看:676
本文介绍了如何在NSTextField中垂直居中对齐文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSTextField,我想垂直居中对齐其中的文本.基本上,我需要如何垂直放置UITextField文本的NSTextField答案?

I have an NSTextField and I want to vertically center align the text in it. Basically I need the NSTextField answer of How do I vertically center UITextField Text?

有人知道吗?谢谢!

推荐答案

您可以将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):

这篇关于如何在NSTextField中垂直居中对齐文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆