How can i create `IBOutlet` or `IBAction` in custom class
-
18-04-2021 - |
Question
how can i create IBOutlet
or IBAction
taking into account following conditions:
IBAction
orIBOutlet
must be created inside my custom class (inherited fromNSObject
)NSButton
instance is visible insideInterface Builder (XCode 4)
In short i would like to add click action from button to my class.
Any help appriciated, thanks :)
EDIT 19.02.2012
I was asking questions without providing all data that was needed... i just needed to read some more cocoa guides...
I wanted to hook up acitions to components from other scopes which is impossible from what i know :(
Solution
Look at Apple's Cocoa tutorial documentation that comes with Xcode 4, this is rather fundamental to the Xcode/Cocoa/interface designer model!
In outline:
@interface MyCustomClass
- (IBAction) myButtonClickAction:(id)sender;
@end
@implementation MyCustomClass
- (IBAction) myButtonClickAction:(id)sender
{
NSLog(@"My button has been clicked");
}
@end
Now in the interface designer (just open the .xib file in Xcode to get the designer) you need to:
- Add an instance of
MyCustomClass
- select Object from the Object Library and drag it onto your Objects (usually on lhs of canvas) or the design canvas (it will just go to Objects and not create a graphic widget on the canvas). Now select the added Object and in the Inspector (usually on rhs of canvas) set the class toMyCustomClass
. Now when your application starts up an instance ofMyCustomClass
will be created. - Select your
NSButton
on the design canvas, select the Connections tab in the Inspector. Click and drag from selector under Sent Actions to yourMyCustomClass
under Objects. On releasing you'll get a menu ofIBAction
s to select from, pickmyButtonClickAction
. - You'll probably want to add an
IBOutlet
to your application delegate to link to the custom object instance that has been created, if you don't you won't have a direct way of accessing it. The process to do this follows the same pattern as for theIBAction
above.
That is it, in words (pictures help), and very briefly.
Now go read those tutorials!
OTHER TIPS
IBOutlet and IBAction are just flags to be used by Interface builder for hooking up UIComponents and their actions to classes (hence the prefix IB). This is all the are used for - you don't use them to programmatically hook up buttons with actions
If you want to hook up a button to an action, you need to add and action to the button.
(not sure of the syntax with NSButton, as I'm an iOS programmer - but search the docs and it should be clear)