Search code examples
objective-cxcodeuibuttonnsobject

How to create UIButton and its @selector in a NSObject


I'm trying to generate a class that can create a UIButton and take care of what happens when you press the button in any view where the button is located. Here is what I'm doing:

Header File:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface CreateButton : NSObject

- (UIButton *)createButton;

@end

Implementation:

#import "CreateButton.h"

@implementation CreateButton

- (UIButton *)createButton
{
    // Instanciate the class
    CreateButton *classInstance = [[CreateButton alloc] init];

    UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
    [testButton setBackgroundColor:[UIColor redColor]];
    [testButton addTarget:classInstance action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    return testButton;
}

- (void)buttonClicked:(UIButton *)sender
{
    NSLog(@"Clicked");
}

@end

And finally, in the a view controller, I initialize the class and get the button:

CreateButton *create = [[CreateButton alloc] init];
UIButton *testButton = [create createButton];
[self.view addSubview:testButton];

Now everything is ok up to this point and I can see the button, however, nothing happens when I click it. Surprisingly, if I move the buttonClicked: method to my view controller it works just fine. I need to keep all the button wiring inside the NSObject. Any help would be greatly appreciated.


Solution

  • Ok, I solved the problem, interesting.

    Implementation file will be modified as:

    - (UIButton *)createButton
    {
        UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
        [testButton setBackgroundColor:[UIColor redColor]];
        [testButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        return testButton;
    }
    

    Then, in the view controller, CreateButton class must be pre-defined in the header file @interface section. Then in the implementation:

    create = [[CreateButton alloc] init];
    

    and it works! That would be great if you kindly explains this to me.