简体   繁体   English

如何在可可的nstextfield上设置字体和颜色?

[英]How set font and color on nstextfield in cocoa?

I want set font on panel and change the selected font. 我想在面板上设置字体并更改所选字体。 I am using NSColorWell to open and select the color. 我正在使用NSColorWell打开并选择颜色。 For font, what can I use? 对于字体,我可以使用什么? How can I open the font panel and perform action when font panel is closed? 关闭字体面板后,如何打开字体面板并执行操作?

Currently I am using 目前我正在使用

'- (IBAction)Open_Font_Button:(id)sender
{
    NSFontManager *fontManager = [NSFontManager sharedFontManager];
    [fontManager setDelegate:self];
    [fontManager setTarget:self];
    [fontManager orderFrontFontPanel:self];
}

- (void)changeFont:(id)sender
{
    font = [sender convertFont:font];
    NSLog(@"%@", font);


}
'

but on chnageFont , when I change any font or its size it crashes. 但是在chnageFont ,当我更改任何字体或其大小时会崩溃。

I assume you have outlets to the ColorWell and textField connected: 我假设您有连接到ColorWell和textField的插座:

IBOutlet NSColorWell *colorWell;
IBOutlet NSTextField *textfield;

You should set some things about the NSColorPanel: 您应该对NSColorPanel进行一些设置:

[NSColor setIgnoresAlpha:NO];
[[NSColorPanel sharedColorPanel] setShowsAlpha:YES];

When you open or close a window that might display a color panel you should be sure you aren't left with a color panel hanging around: 当您打开或关闭可能显示颜色面板的窗口时,应确保没有周围出现颜色面板:

if ([NSColorPanel sharedColorPanelExists])
{
    [[NSColorPanel sharedColorPanel] close];
}

Then in your IBAction method for the color well you can get the color: 然后,在颜色的IBAction方法中,您可以获取颜色:

NSColor *color;
color = [colorWell color];

You can then set the font and color with: 然后,您可以使用以下方法设置字体和颜色:

[textField setFont:anNSFont *];
[textField setTextColor:color];

EDIT: 编辑:

I just realized you're also asking how to get a new font from the font panel. 我刚刚意识到您也在询问如何从字体面板中获取新字体。

To get a new font from the font panel your code should actually work fine unless "font" (the old font) was never initialized. 要从字体面板中获取新字体,除非从未初始化“字体”(旧字体),否则您的代码实际上应该可以正常工作。 If font is null then [sender convertFont:font] will return null. 如果font为null,则[sender convertFont:font]将返回null。

This prints null: 这将输出null:

- (void)changeFont:(id)sender
{
    NSFont *font;

    font = [sender convertFont:font]; // Reset the font

    NSLog(@"%@", font);

}

This prints a font: 这将打印一种字体:

- (void)changeFont:(id)sender
{
    NSFont *font = [NSFont fontWithName:@"Helvetica" size:12]; // Initialize the old font

    font = [sender convertFont:font]; // Reset the font

    NSLog(@"%@", font);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM