macos 如何在 Cocoa 中自定义 NSTextField 外观(使用的字体、字体大小)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1100903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:15:44  来源:igfitidea点击:

How to customize NSTextField look (Font used, font size) in Cocoa?

objective-ccocoamacosnstextfield

提问by Fantattitude

I'm making a Cocoa application and I can't figure out how to do something.

我正在制作 Cocoa 应用程序,但我不知道该怎么做。

I want to make an NSTextField with a custom look like the one in Wallet :

我想制作一个具有自定义外观的 NSTextField ,就像 Wallet 中的一样:

Wallet screenshot.

钱包截图。

I figured out how to change the NSTextField size but I don't know how to change the font and it size. I subclassed NSTextFieldCell like this but it doesn't work, the font is not changed if I don't choose a system font and the size only change line height but not characters height.

我想出了如何更改 NSTextField 大小,但我不知道如何更改字体和大小。我像这样将 NSTextFieldCell 子类化,但它不起作用,如果我不选择系统字体,则字体不会更改,并且大小仅更改行高而不更改字符高度。

Header file :

头文件:

#import <Cocoa/Cocoa.h>

@interface VLTextFieldCell : NSTextFieldCell {
}
@end

Class file :

类文件:

#import "VLTextFieldCell.h"

@implementation VLTextFieldCell

- (NSFont *)font
{
    return [NSFont fontWithName:@"Lucida Grande" size:16.0];
}

@end

回答by Jim Correia

To change the font of an NSTextField, change its font in Interface Builder using the Font Panel, or via -setFont: at runtime.

要更改 NSTextField 的字体,请在 Interface Builder 中使用字体面板或通过 -setFont: 在运行时更改其字体。

It is not necessary to subclass NSTextField or NSTextFieldCell simply to use a different font.

没有必要仅仅为了使用不同的字体而将 NSTextField 或 NSTextFieldCell 子类化。

回答by Charles

[label setFont:[NSFont fontWithName:@"Arial-BoldItalicMT" size:20]];

setFont:is declared in NSControl, super class of NSTextField.

setFont:在 的NSControl超类中声明NSTextField