Why can't I add custom NSButtonCell to NSView? - objective-c

I'm attempting to create a custom view that contains a play/pause button, and I'll attach any number of these to an NSWindow. I started by creating my own NSView and just drawing out the various pieces, then subclassing the play/pause button as an NSView (baby steps).
This all worked fine until I decided my button needed to extend NSButtonCell rather than an NSView. The following (from TimeSlipView.m) fails miserably, and I can't seem to figure out why:
playPauseButton = [[TimeSlipViewButton alloc] init];
[playPauseButton setButtonType:NSMomentaryPushInButton];
[self addSubview:playPauseButton];
I get a compile error and this warning for that last line: "Incompatible pointer types sending 'TimeSlipViewButton *__strong' to paremeter of type 'NSView *'".
I have a feeling I've misunderstood something very basic, and that for some reason I can't just pass addSubview: my NSButtonCell from within an NSView.
TimeSlipView.h
#import <Cocoa/Cocoa.h>
#import "TimeSlipViewButton.h"
#interface TimeSlipView : NSView {
TimeSlipViewButton *playPauseButton;
NSView *timerText;
NSView *clientText;
NSView *projectText;
NSView *taskText;
}
#end
TimeSlipViewButton.h
#import <Cocoa/Cocoa.h>
#interface TimeSlipViewButton : NSButtonCell
#end

A Cell Is no View and thus cannot be used as such! what you do doesn't work
You try exactly that when adding it as a subview
Cells are a (legacy) concept where views were too expensive.
The were/are used by some controls (like NSButton) to handle the actually drawing.
the Button CONTAINS a button cell
It ISNT a button cell, it IS a NSView
what you might wanna do is give a stock NSButton a specific ButtonCell that has custom drawing options. There are good tutorials out there for given existing NSButtons/NSSegmentedCells/NSTextFields custom NSCells

Related

Why is this delegate method automatically called in Objective-C?

I'm going through this book called "cocoa programming for mac os x" and I just started with delegates. This whole thing with delegates is still a little bit wacky to me but I think I just need to let it settle.
However there was this one exercise where I should implement a delegate of the main window so that if resized height is always 2xwidth.
So I got 4 files:
AppDelegate.h
AppDelegate.m
WindowDelegate.h
WindowDelegate.m
AppDelegate are just the two standard files that get created when you open a new Cocoa project. I had to look up the solution because I didn't quite know how to accomplish this task.
The solution was just to create a new cocoa class, "WindowDelegat.h/.m" and add this to it's implementation file:
- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)frameSize {
NSSize newSize = frameSize;
newSize.height = newSize.width * 2;
return newSize;
}
Then I opened the interface builder, added a new object and made it my WindowDelegate. I then had to ctrl drag from the WindowDelegate to the actual window and made it the window's delegate.
Clicked run and it worked. Yay! But why?
First I thought that "windowWillResize" is just one of these callback functions that get's called as soon as the window is resized but it isn't. Normally methods get invoked because the general lifecycle of an program invokes them or because they are an #IBAction, a button or different control elements.
But "windowWillResize" is non of them. So why is it called?
EDIT: Problem solved! Thanks a lot!
Now I'm trying to connect the delegate to the window programmatically. Therefore I deleted the referencing outlet from WindowDelegate to the actual window in interface builder. It works but I just want to verify that this it the correct way how it's done:
AppDelegate.h
#import <Cocoa/Cocoa.h>
#import "WindowDelegate.h"
#interface AppDelegate : NSObject <NSApplicationDelegate>
#end
AppDelegate.m
#import "AppDelegate.h"
#interface AppDelegate ()
#property (weak) IBOutlet NSWindow *window;
#property (strong) WindowDelegate *winDeleg;
#end
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
- (void)awakeFromNib {
[_window setOpaque:NO];
NSColor *transparentColor = [NSColor colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.5];
[_window setBackgroundColor:transparentColor];
NSSize initialSize = NSMakeSize(100, 200);
[_window setContentSize:initialSize];
_winDeleg = [[WindowDelegate alloc] init];
[_window setDelegate: _winDeleg];
}
#end
WindowDelegate.h
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#interface WindowDelegate : NSObject <NSWindowDelegate>
#end
WindowDelegate.m
#import "WindowDelegate.h"
#implementation WindowDelegate
- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)frameSize {
NSSize newSize = frameSize;
newSize.height = newSize.width * 2;
return newSize;
}
- (id)init {
self = [super init];
return self;
}
#end
Why does the #property of WindowDelegate need to be strong?
And isn't my winDeleg an object? Why do I have to access it through _winDeleg when it's an object. I though the underscore is used to access variables?
Thank you for your help!
Clicked run and it worked. Yay! But why?
Because instances of NSWindow have a delegate property that can point to any object that implements the NSWindowDelegate protocol, and that protocol includes the -windowWillResize:toSize: method.
Read that a few times. The reason it's important is that you can create your own object, say that it implements NSWindowDelegate, implement -windowWillResize:toSize:, and set that object as your window's delegate. Then, whenever the user resizes the window, your method will be called and can modify the proposed new size.
Normally methods get invoked because the general lifecycle of an program invokes them or because they are an #IBAction, a button or different control elements. But "windowWillResize" is non of them. So why is it called?
This really isn't so different. Think of delegates as "helper objects." They let you customize the behavior of an object without having to create a whole new subclass. The NSWindowDelegate object is essentially a contract that the NSWindow promises to follow: whenever certain things happen, such as the user resizing the window, the window will call certain methods in its delegate object, if the delegate exists and implements those methods. In the case of NSApplication, a lot of those delegate methods are application lifecycle events, like the app starting up or quitting or getting a message from the operating system. In the case of NSWindow, delegate methods correspond to interesting events that can happen to a window, like the user moving it, hiding it, showing it, maximizing it, moving it to a different screen, etc. Other classes, like text views or network connections or movie players, have their own sets of interesting events and their own delegate protocols to match.
Note that methods marked IBAction really aren't delegate methods, they're just methods that get called by objects like controls that use a target/action paradigm. The IBAction keyword lets the IDE know which methods it should present as possible actions for things like buttons. You often find actions in window controllers and view controllers, and those objects frequently act as a delegate for some other object, but the actions themselves aren't part of the delegate protocol. For example, NSTableView takes a delegate object that determines how the table will act and what's displayed in it. It often makes sense for the view controller that manages the table to be the table's delegate, and that same view controller might also manage some buttons and contain the action methods that said buttons trigger, but the actions aren't part of the NSTableViewDelegate protocol and you therefore wouldn't call them delegate methods.

How to access objects from different classes in Cocoa Programming

I have an NSTextField subclass (called "txtField1" and used as Custom Class for a Text Field in my interface builder) and I would like to be able to access an NSComboBox object which present in my interface builder from this class.
This is my code:
txtField1.h:
#import <Cocoa/Cocoa.h>
#interface txtField1 : NSTextField
#end
txtField.m:
#import "txtField1.h"
#implementation txtField1
-(void)mouseDown:(NSEvent *)theEvent
{
HERE I would like to be able to write something like:
[combobox SetHidden:YES];
}
#end
I would like to be able to set access the combobox SetHidden property, in the mouseDown event.
Can you please tell me how to do that? I have tried different solutions found on internet but didn't obtain anything at all!
Any help would be appreciated.
Here are a lot of ways, and answers here, to do :
Update a label through button from different view
Xcode - update ViewController label text from different view
Setting label text in another class
Set label on another view to stored NSDate
EDIT:
-(void)mouseDown:(NSEvent *)theEvent
{
HERE I would like to be able to write something like:
[combobox SetHidden:YES];
/*
use the shared instance of comboBox here and make it hidden.
Also, you can use binding to make it hidden
*/
}
From my point of view txtField1 class is not better place to this code.
You can add NSControlTextEditingDelegate protocol to your NSViewController implementation (that already contains IBOutlets for txtField1 and combobox) and in method – control:textView:doCommandBySelector: implement hiding of your NSComboBox

Implement a keyboard click sound, lost

Everyone on this site has been very helpful on my schooling of iOS programming, but I've run into a brick wall with a very simple feature. I've found Apples documentation on implementing the factory keyboard click sound upon a button touch, but what Im not getting is the "creating a sub lass of UIView" part. I have a very basic calculator that I've built, the buttons are made of standard Round Rect's that I want to make the simple click sound. So Apple says:Adopting the UIInputViewAudioFeedback Protocol
Perform the following three steps to adopt the UIInputViewAudioFeedback protocol:
In your Xcode project, create a subclass of the UIView class. In the header file, indicate that the subclass conforms to the UIInputViewAudioFeedback protocol, as follows:
#interface KeyboardAccessoryView : UIView {
}
Now I am using the standard UIViewController tied to a xib with all my buttons. Am i to: Create New File, name it as a subclass of UIView, JUST so i can implement this sound? That doesn't make sense to me, and if this is really amateur stuff I apologize, but I'm learning from many different places. Thanks in advance.
You have to set your custom input view as the inputView property of the object that is supposed to be the first responder (For example, a UITextField instance), and the inputView(your custom input view) must conform to the UIInputViewAudioFeedback protocol. And to actually play a click sound: [[UIDevice currentDevice] playinputClick].
For example:
#interface MyCalculatorDisplay : UIView
// ...
#end
#interface MyCustomKeyboard : UIView <UIInputViewAudioFeedback>
// ...
#end
// Then, somewhere in your controller:
MyCustomKeyboard *keyboard = [MyCustomKeyboard new];
MyCalculatorDisplay *display = [MyCalculatorDisplay new];
display.inputView = keyboard;

Swapping views - NSWindowController and NSViewController(s)

I'm very new in Mac OS programming. At the moment I'm trying to create simple measurement application which will have one window with the toolbar at the top and the appropriate view in the bottom. Clicking button in the toolbar should result in switching view below it - e.g. clicking on the "Connection" button will show with connection settings, "Measurements" will show current data from the device.
The problem is - I don't know how to handle swapping views, maybe in other words - something I know but not exactly...
I found similar discussion here: NSViewController and multiple subviews from a Nib but there is no answer how to create NSWindowController and how to assign it to the Main window. Because I guess it is necessary to create NSWindowController to be able to swapping views. If I'm wrong, please correct me.
So I'm creating new project (called Sample here) and there is SampleAppDelegate.h file, which looks like:
#interface SampleAppDelegate : NSObject <NSApplicationDelegate> {
#private
NSWindow *window;
}
#property (assign) IBOutlet NSWindow *window;
#end
There is window ivar, which holds the only one window, created from the MainMenu.xib (as I think).
So how should I create NSWindowController for the window from the SampleAppDelegate?
Should I just create my WindowController subclass and in the function
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
of the SampleAppDelegate like this:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
MyWindowController *wc = [[MyWindowController alloc] initWithWindow:self.window];
[wc showWindow:self];
self.myWindowController = wc;
[wc release];
}
I'll be very grateful for any hints and help.
Marcin
You shouldn't need an NSWindowController to do view swapping, NSWindowController used (I think) just when you need multiple toplevel windows.
You can just subclass NSViewController for each type of view that you want, put each view into a nib, and call -(NSView *)view when you need a view to put into the bottom part of the window. You should be able to just add it to the window like normal, or put it in an NSBox by using setContentView:view
For your two views you'd create MeasurmentsViewController and a ConnectionViewController. Then you'd create your views in MeasurementsView.nib and ConnectionView.nib, and use those nibs to initialise your view controllers.
Then in your main window, if you were to put an NSBox, if you wanted to put the MeasurementsView into it
NSView *measurementsView = [measurementsViewController view];
[boxAtBottomOfWindow setContentView:measurementsView];
and to put the ConnectionView into it
NSView *connectionView = [connectionViewController view];
[boxAtBottomOfWindow setContentView:connectionView];

Where are events in Cocoa Touch?

I learn Cocoa Touch several days, and today have stuck while looking for way to implement a custom event. Event that I can see in Connection Inspector for my UIView subclass.
What I have:
There are a UILabel and MyView:UIView on MainVindow. MyView contains a UISlider. Interfaces for Controller and MyView
// Controller.h
#interface Controller : NSObject {
IBOutlet UILabel *label;
IBOutlet MyView *myView;
}
// I suppose that there should be something like -(IBAction) changeLabelValue for myView event
#end
// MyView.h
#interface MyView : UIView {
IBOutlet UISlider *slider;
float value;
}
- (IBAction) changeValue; //for slider "Changed Value" event
What I want:
Add something in MyView that allows it to rise a event after change value.
Can anybody help me? My main area in programming is .NET and I begin think that its terminology is not appropriate for this case.
Thanks.
I don’t know if I'm understanding you correctly but I think what you want is responding to user events from interface components. In Cocoa the term "event" is only used for objects that describe the actual event, like a touch down or key up.
To respond to higher level events, like dragging a slider or pushing a button, Cocoa uses the target action paradigm. You set up a UI component (a UIControl derived view class) to send a given message to a given target whenever the component detects a change of its state.
To set the target and the action method you can use Interface Builder or the UIControl method addTarget:action:forControlEvents:.