简体   繁体   中英

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. 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.

I assume you have outlets to the ColorWell and textField connected:

IBOutlet NSColorWell *colorWell;
IBOutlet NSTextField *textfield;

You should set some things about the 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:

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.

This prints 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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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