Saving NSTextField properties based on NSPopUpButton selection using NSUserDefaults - cocoa

I have added an option to my app to change the background color and textColor of an NSTextField. I set up an NSPopUpButton and based on the selected item in the NSPopUpButton, it changes the colors. I want to save this selection using NSUserDefaults. I am using this method to change the backgroundColor and textColor and it works. How would I save the properties with NSUserDefaults and have it set on start up?
- (IBAction)addBarColor:(id)sender {
if ([addBarColor.titleOfSelectedItem isEqualToString:#"White"]) {
addressBar.backgroundColor = [NSColor whiteColor];
addressBar.textColor = [NSColor blackColor];
}
else {
//default state
addressBar.backgroundColor = [NSColor redColor];
addressBar.textColor = [NSColor whiteColor];
}
}

First set in your action method like that below:-
Now in this action whenever you set the color, it will save into default color just added here two lines
- (IBAction)addBarColor:(id)sender {
NSUserDefaults *default=[NSUserDefaults standardUserDefaults];
[default setObject:addBarColor.titleOfSelectedItem forKey:#"selectedColor"];
//Process your code
}
//Now in this just reading the saved color from defaults and then setting into your popup button
-(void)awakeFromNib
{
NSUserDefaults *default=[NSUserDefaults standardUserDefaults];
NSString *defColor=[default ObjectForKey:#"selectedColor"];
if (defColor)
{
[addBarColor selectItemWithTitle:defColor];
}
}

Related

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);
}

NSButton disabled title color always gray

I have a custom NSButton, but no matter what i do, the disabled color is always gray
I tried all solutions i came across
i'am setting the attributed string title with white foreground color (i looks like the color attribute is ignored for the disabled state)
i did set [[self cell] setImageDimsWhenDisabled:NO];
event when the documentations states
// When disabled, the image and text of an NSButtonCell are normally dimmed with gray.
// Radio buttons and switches use (imageDimsWhenDisabled == NO) so only their text is dimmed.
#property BOOL imageDimsWhenDisabled;
it doesn't work
My NSButton uses wantsUpdateLayer YES, so the draw methods are overwritten, but i don't understand, where the title is drawn
On OS X 10.9 I've managed to alter the color of the button's text when it's disabled by sub-classing the cell that draws the button.
Create a new NSButtonCell subclass in Xcode and override the following method:
- (NSRect)drawTitle:(NSAttributedString *)title
withFrame:(NSRect)frame
inView:(NSView *)controlView {
NSDictionary *attributes = [title attributesAtIndex:0 effectiveRange:nil];
NSColor *systemDisabled = [NSColor colorWithCatalogName:#"System"
colorName:#"disabledControlTextColor"];
NSColor *buttonTextColor = attributes[NSForegroundColorAttributeName];
if (systemDisabled == buttonTextColor) {
NSMutableDictionary *newAttrs = [attributes mutableCopy];
newAttrs[NSForegroundColorAttributeName] = [NSColor orangeColor];
title = [[NSAttributedString alloc] initWithString:title.string
attributes:newAttrs];
}
return [super drawTitle:title
withFrame:frame
inView:controlView];
}
Select the button in Xcode, then select its cell (maybe easiest to do this in the Interface Builder dock), now got to the Identity Inspector and set the cell's class to that of your subclass.
This is because of the default true value of
- (BOOL)_shouldDrawTextWithDisabledAppearance
Try to change this method instead of imageDimsWhenDisabled. If you are using Swift 4, I would do the following in the Bridging header:
#import <AppKit/AppKit.h>
#interface NSButtonCell (Private)
- (BOOL)_shouldDrawTextWithDisabledAppearance;
#end
And in the subclass of NSButtonCell:
override func _shouldDrawTextWithDisabledAppearance() -> Bool {
return false
}
And that's it: the grey should disappear

NSTextField in NSTableCellView

I have a view based NSTableView with a custom NSTableCellView. This custom NSTableCellView has several labels (NSTextField). The whole UI of the NSTableCellView is built in IB.
The NSTableCellView can be in a normal state and in a selected state. In the normal state all text labels should be black, in the selected state they should be white.
How can I manage this?
Override setBackgroundStyle: on the NSTableCellView to know when the background changes which is what affects what text color you should use in your cell.
For instance:
- (void)setBackgroundStyle:(NSBackgroundStyle)style
{
[super setBackgroundStyle:style];
// If the cell's text color is black, this sets it to white
[((NSCell *)self.descriptionField.cell) setBackgroundStyle:style];
// Otherwise you need to change the color manually
switch (style) {
case NSBackgroundStyleLight:
[self.descriptionField setTextColor:[NSColor colorWithCalibratedWhite:0.4 alpha:1.0]];
break;
case NSBackgroundStyleDark:
default:
[self.descriptionField setTextColor:[NSColor colorWithCalibratedWhite:1.0 alpha:1.0]];
break;
}
}
In source list table views the cell view's background style is set to Light, as is its textField's backgroundStyle, however the textField also draws a shadow under its text and haven't yet found exactly what is controlling that / determining that should it happen.
Probably the easiest way to accomplish this would be to subclass NSTextField and to override the drawRect: method in your subclass. There you can determine whether the NSTableCellView instance containing your NSTextField instances is currently selected by using this code (which I use with a NSOutlineView, but it should also work with NSTableView):
BOOL selected = NO;
id tableView = [[[self superview] superview] superview];
if ([tableView isKindOfClass:[NSTableView class]]) {
NSInteger row = [tableView selectedRow];
if (row != -1) {
id cellView = [tableView viewAtColumn:0 row:row makeIfNecessary:YES];
if ([cellView isEqualTo:[self superview]]) selected = YES;
}
}
Then draw the view like this:
if (selected) {
// set your color here
// draw [self stringValue] here in [self bounds]
} else {
// call [super drawRect]
}
This works no matter what style the table view has:
- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle {
[super setBackgroundStyle:backgroundStyle];
NSTableView *tableView = self.enclosingScrollView.documentView;
BOOL tableViewIsFirstResponder = [tableView isEqual:[self.window firstResponder]];
NSColor *color = nil;
if(backgroundStyle == NSBackgroundStyleLight) {
color = tableViewIsFirstResponder ? [NSColor lightGrayColor] : [NSColor darkGrayColor];
} else {
color = [NSColor whiteColor];
}
myTextField.textColor = color;
}
Swift 4
override var backgroundStyle: NSView.BackgroundStyle {
get {
return super.backgroundStyle
}
set {
self.yourCustomLabel.textColor = NSColor(calibratedWhite: 0.0, alpha: 1.0)//black
}
}

Change a loaded image based on a NSUserDefaults setting

Hope you can help me with this.
I have an app that needs to show one of two maps via the setting of a UISwitch. The settings.bundle is all set up and I am trying to write an If statement to determine if the switch is on or off, and to display the right image.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL Enabled = [defaults boolForKey:#"zones_preference"];
if (Enabled == #"Enabled") {
[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"withzones.jpg"]];
}
else {
[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"withoutzones.jpg"]];
}
This builds without error, but doesn't load the image into the ScrollView. Could anyone advise on where I am going wrong?
Well, the code you've posted only creates a UIImageView object and doesn't do anything more. It's a leak too.
There's one more error in the line
if (Enabled == #"Enabled") {
Here, you are comparing a boolean to a string which will evaluate to false automatically so it needs to be corrected too.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL enabled = [defaults boolForKey:#"zones_preference"];
UIImageView * imageView;
if ( enabled ) {
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"withzones.jpg"]];
} else {
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"withoutzones.jpg"]];
}
imageView.frame = imageViewFrame; // Where "imageViewFrame" is an appropriate frame.
[scrollView addSubview:imageView];
[imageView release];
Deepak, that was very useful and thank you. I had been working with a variable, but the mistake I had made was that I was trying to add the setup of the variable in with the creation of the UIImageView.
I'll work with this and see how I get on.

Saving title of NSSegmentedControl in User defaults

Thanks for the help:
I manually set the title of a segController segment from a textField input like this:
NSString *labelString = [textField stringValue];
(textField.stringValue = labelString);
[segControl setLabel: labelString forSegment:8];
I loose the new label when quitting. How can I save the edited segController label string in NSUserDefaults as I would with a text string, like this:
[[NSUserDefaults standardUserDefaults] setObject: [textField objectValue] forKey: #"newDefault"];
My action needs to occasionally set a new title. Point is the label string is not permanently fixed.
thanks.
Paul.
Assuming you know the segment number, You can do the following:
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if(defaults) {
[defaults setValue: [segControl labelForSegment:8] forKey: #"segmentLabel"];
}
else {
// handle error
}
Alternatively you can just save the string to NSUserDefaults whenever you set the label like in your above example.

Resources