UIButton with action-selector method in different class - ios

Related to this previous question (Creating UI elements programmatically in Objective-C), this method resides in one class of the project, and other classes are able to call it to programmatically create buttons:
UIButton *createButton(CGFloat x, CGFloat y, CGFloat width, CGFloat height, NSString *caption, NSTextAlignmentCenter textPosition, UIColor *textColor, UIColor *backColor) {
UIButton *control = [[UIButton alloc] initWithFrame: CGRectMake(x, y, width, height)];
[control setTitle:caption forState:UIControlStateNormal];
control.titleLabel.textAlignment = textPosition;
control.backgroundColor = backColor;
[control setTitleColor: textColor forState:UIControlStateNormal];
return control;
}
I am now trying to add the target and action methods, to be handled by a common function, like so:
[control addTarget:nil
action:#selector(commonHandler)
forControlEvents:UIControlEventTouchDown];
It works for buttons that reside in the same class as the createButton() function, but although the buttons are successfully created in the other classes as well, they don't trigger the commonHandler() method.
NOTE: the createButton() and commonHandler() methods have been declared in its header file, and imported by all classes.
Is there any way to achieve this?
EDIT: The proposed solution still crashes
I modified the code as per the suggestions, and converted both the createButton and buttonAction to Objective-C methods, to enable reference to self.
class1 header
// class1.h
#import <UIKit/UIKit.h>
#import "class2.h"
#interface class1 : UIViewController {
UIButton *button1;
}
- (void) buttonAction:(UIButton *)control;
- (UIButton *) createButtonWithxPos:(CGFloat)x
yPos:(CGFloat)y
width:(CGFloat)width
height:(CGFloat)height
caption:(NSString *)caption
textPos:(NSTextAlignment)textPosition
textClr:(UIColor *)textColor
backClr:(UIColor *)backColor;
#end
class1 implementation
// class1.m
#import "class1.h"
#import "class2.h"
#implementation class1
- (void)viewDidLoad {
[super viewDidLoad];
button1 = [self createButtonWithxPos:10
yPos:10
width:200
height:30
caption:#"Cls1 Button"
textPos:NSTextAlignmentCenter
textClr:[UIColor whiteColor]
backClr:[UIColor blackColor]];
[self.view addSubview: button1];
}
- (UIButton *) createButtonWithxPos:(CGFloat)x
yPos:(CGFloat)y
width:(CGFloat)width
height:(CGFloat)height
caption:(NSString *)caption
textPos:(NSTextAlignment)textPosition
textClr:(UIColor *)textColor
backClr:(UIColor *)backColor
{
UIButton *control = [[UIButton alloc] initWithFrame: CGRectMake(x, y, width, height)];
[control setTitle:caption forState:UIControlStateNormal];
control.titleLabel.textAlignment = textPosition;
control.backgroundColor = backColor;
[control setTitleColor: textColor forState:UIControlStateNormal];
[control addTarget:self action: #selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
return control;
}
- (void) buttonAction:(UIButton *)control {
NSLog(#"button clicked...");
}
#end
class2 header
// class2.h
#import <UIKit/UIKit.h>
#interface class2 : UIViewController {
UIButton *button2;
}
#end
class2 implementation
// class2.m
#import "class1.h"
#import "class2.h"
#implementation class2
- (void) viewDidLoad {
[super viewDidLoad];
class1 *cls1 = [[class1 alloc] init];
button2 = [cls1 createButtonWithxPos:10
yPos:10
width:200
height:30
caption:#"Cls2 Button"
textPos:NSTextAlignmentCenter
textClr:[UIColor whiteColor]
backClr:[UIColor blackColor]];
[self.view addSubview: button2];
}
#end
Both button1 and button2 are created properly, but button1 triggers the buttonAction method while button2 does not - it crashes on touch.
Is it implemented wrongly?
(please excuse any omissions as I have only extracted the relevant portions from the actual project to illustrate here)

Related

Protocols is not working

Hi I am adding one custom button programmatically on navigation bar and i have written all button properties in my background class and i am calling this method from my main class
And here I have used protocols for getting button touching event in my main class from background class but it's not working using protocols
my code:-
background class:-
BackGroundClass.h
#import <UIKit/UIKit.h>
#protocol buttonprotocol<NSObject>
#required
- (void) buttonTapped;
#end
#interface BackGroundClass : UIViewController
#property (nonatomic, weak) id<buttonprotocol> delegate;
#end
BackGroundClass.m
#import "BackGroundClass.h"
#interface BackGroundClass ()
#end
#implementation BackGroundClass
#synthesize delegate;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)backbutton: (UINavigationItem *)navigationitem
{
UIImage* image3 = [UIImage imageNamed:#"back.png"];
CGRect frameimg = CGRectMake(15,5,25,25);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:#selector(Back_btn:)
forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
navigationitem.leftBarButtonItem = mailbutton;
}
- (void)Back_btn :(id)sender
{
[delegate buttonTapped];
}
#end
main class:-
mainclass.h
#import <UIKit/UIKit.h>
#import "BackGroundClass.h"
#interface mainclass : UIViewController<buttonprotocol>
mainclass.m
#import "mainclass.h"
#import "BackGroundClass.h"
#interface mainclass ()
{
BackGroundClass * bg;
}
#end
#implementation mainclass
- (void)viewDidLoad {
[super viewDidLoad];
bg = [[BackGroundClass alloc]init];
[bg backbutton:self.navigationItem];
}
- (void)buttonTapped
{
NSLog(#"ok it's 2");
}
but that above button tapped a method isn't called what I did wrong?
When you are creating the object of your BackGroundClass class, then you are not setting the delegate of the class to self, thats why your delegate method is not calling, try it like this
bg = [[BackGroundClass alloc]init];
bg.delegate = self;
First of all, using Class in class names is bad practice. As for View Controllers you should use either ViewController or VC postfix for your class names.
For example, the proper names of your Objective-C classes would be: BackgroundViewController, MainViewController
Secondly, ViewController instances are used to react to user interaction with the view attached to this ViewController and provide visible changes based on Data component of MVC work.
So, there is no reason to use second, in your case BackgroundViewController (BackgroundClass).
For more info about MVC pattern, please refer this link:
Apple's MVC articles
As there is no need in external ViewController we also should remove the delegate using and place all logic inside this main View Controller.
Thirdly, as mentioned in Apple's Mobile HIG, buttons should have a height around 44px, so your back button's size of 25x25 would make most users experience hard trying to tap on it.
At last, you should receive the class with code similar to it:
MainViewController.h
#import <UIKit/UIKit.h>
#interface MainViewController : UIViewController
#end
MainViewController.m
#import "MainViewController.h"
#implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *icon = [UIImage imageNamed:#"back.png"];
static CGFloat defaultButtonSize = 44.; // Default button's tap area size
CGSize buttonSize = CGSizeMake(defaultButtonSize, defaultButtonSize);
// The size image should take inside the button
CGSize imageSizeInsideButton = CGSizeMake(25., 25.);
CGRect frameimg = CGRectMake(15., 5., defaultButtonSize, defaultButtonSize);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setImage:icon forState:UIControlStateNormal];
[someButton addTarget:self
// No need to put colon after method name,
// since you have no use of control that triggered action
action:#selector(backButtonClicked)
forControlEvents:UIControlEventTouchUpInside];
someButton.showsTouchWhenHighlighted = YES;
// Calculate edge insets so image will take the size
// you specified dozen of lines before
CGFloat imageVerticalPaddingInButton = (buttonSize.height - imageSizeInsideButton.height) / 2.;
CGFloat imageHorizontalPaddingInButton = (buttonSize.height - imageSizeInsideButton.height) / 2.;
// Apply it to button
someButton.imageEdgeInsets = UIEdgeInsetsMake(imageVerticalPaddingInButton,
imageHorizontalPaddingInButton,
imageVerticalPaddingInButton,
imageHorizontalPaddingInButton);
UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem = mailbutton;
}
// As stated in "addTarget", there is no "sender" since you don't really need it
// If you ever would need the use of it,
// don't forget to put colon in "addTarget" UIButton's method
// and place something like :(UIButton *)buttonThatClicked
// after methodName
- (void)backButtonClicked {
// Get back to your previous view controller or do whatever you like there
[self.navigationController popViewControllerAnimated:YES];
}
#end
But if you want to use this thing in as many View Controllers as possible, then you should create the category:
UIViewController+CustomBackButton.h
#import <UIKit/UIKit.h>
#interface UIViewController (CustomBackButton)
- (void)setBackButtonImage:(UIImage *)image withSize:(CGSize)size target:(id)target selector:(SEL)selector;
#end
UIViewController+CustomBackButton.m
#import "UIViewController+CustomBackButton.h"
#implementation UIViewController (CustomBackButton)
- (void)setBackButtonImage:(UIImage *)image withSize:(CGSize)size target:(id)target selector:(SEL)selector {
static CGFloat defaultButtonSize = 44.;
CGSize buttonSize = CGSizeMake(defaultButtonSize, defaultButtonSize);
CGRect frameimg = CGRectMake(15., 5., defaultButtonSize, defaultButtonSize);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setImage:image forState:UIControlStateNormal];
[someButton addTarget:target
action:selector
forControlEvents:UIControlEventTouchUpInside];
someButton.showsTouchWhenHighlighted = YES;
CGFloat imageVerticalPaddingInButton = (buttonSize.height - size.height) / 2.;
CGFloat imageHorizontalPaddingInButton = (buttonSize.height - size.height) / 2.;
someButton.imageEdgeInsets = UIEdgeInsetsMake(imageVerticalPaddingInButton,
imageHorizontalPaddingInButton,
imageVerticalPaddingInButton,
imageHorizontalPaddingInButton);
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem = backButton;
}
#end
And then your View Controller's implementation file will be much cleaner.
MainViewController.m
#import "MainViewController.h"
#import "UIViewController+CustomBackButton.h"
#implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *icon = [UIImage imageNamed:#"back.png"];
CGSize iconSize = CGSizeMake(25., 25.);
[self setBackButtonImage:icon
withSize:iconSize
target:self
selector:#selector(backButtonClicked)];
}
- (void)backButtonClicked {
// Get back to your previous view controller or do whatever you like there
[self.navigationController popViewControllerAnimated:YES];
}
#end
And then you can use this on every ViewController to customize your back button.

UIButton not being instantiated

I'm trying to instante a simple UIButton from a UIView already created in Interface Builder, but nothing's happening.
I've attached the following codes to the view:
"DetailViewTwo.h":
#import <UIKit/UIKit.h>
#interface DetailViewTwo : UIView
#property (nonatomic) bool viewIsShown;
#property (nonatomic) float lastY;
#property (weak, nonatomic) IBOutlet UILabel *titleLabel;
#property (strong, nonatomic) NSMutableArray *radioArray;
-(void)createOption:(NSString *)legenda Value:(NSString *)value action:(SEL)action;
-(void)clearView:(NSString *)novoNome;
-(void)escolherRota:(id)sender;
#end
"DetailViewTwo.m":
#import "DetailViewTwo.h"
#import "MainViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation DetailViewTwo
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_viewIsShown=false;
[self.layer setMasksToBounds:YES];
self.layer.cornerRadius=6;
UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
but.frame= CGRectMake(100, 15, 15, 15);
[but setTitle:#"Ok" forState:UIControlStateNormal];
[but addTarget:self action:#selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:but];
}
return self;
}
#end
(Oh, also, my 'self.layer.cornerRadius=6;' is not working either, is it related??)
If you have this view created in storyboard you should use
-initWithCoder: initialiser instead of -initWithFrame:.
Also you should add the button to self.view not superview.
- (id)initWithCoder:(NSCoder *)aDecoder {
if(self = [super initWithCoder:aDecoder]) {
//Your code goes here
}
}
You need to add UIButton to View
[self.superview addSubview:but];
should be
[self addSubview:but];
i have a solution to instantiate (add) button in view. As per your code, you just need to replace [self.superview addSubview:but]; with this [self.view addSubview:but];.
UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
but.frame= CGRectMake(100, 15, 15, 15);
[but setTitle:#"Ok" forState:UIControlStateNormal];
[but addTarget:self action:#selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:but]; // Changes done

RemoveFromSuperView not working on UIButton

It seems like such a simple thing to remove a button from a view, but it is not working.
MyViewController.h
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController
#property (strong, nonatomic, readonly, getter = getMyButton) UIButton* myButton;
- (id) init;
- (id) getMyButton;
#end
MyViewController.m
#import "MyViewController.h"
#interface MyViewController ()
#end
#implementation MyViewController
#synthesize myButton = _myButton;
- (id) init
{
if([super initWithNibName: nil bundle: nil])
{
_myButton = nil;
}
return self;
}
- (id) getMyButton
{
if(!_myButton) _myButton = [self createMyButton];
return _myButton;
}
- (void) viewDidLoad
{
[super viewDidLoad];
UIButton* myButton = self.myButton;
[self.view addSubview: myButton];
}
- (void) didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (UIButton*) createMyButton
{
UIButton *button = [[UIButton alloc] init];
[button setTitle: #"My Button"
forState: UIControlStateNormal];
[button addTarget: self
action: #selector(myAction:)
forControlEvents: UIControlEventTouchUpInside];
button.frame = CGRectMake(10, 10, 100, 40);
return button;
}
- (void) myAction: (id) sender
{
[self.myButton performSelectorOnMainThread: #selector(removeFromSuperview) withObject: nil waitUntilDone: NO];
}
#end
But no luck. Clicking the button simply does nothing.
If it is not a problem of concurrency then maybe it is a memory management problem? Maybe it is just something daft, I don't know.
I tried putting the following line into the myAction method
NSLog(#"Test 1");
if(_startButton.superview) NSLog(#"Test 2");
Only 'Test 1' is logged. Perhaps that is a clue but what I don't know is why the button has no superview when it is added to view and is visible on the screen
Additional information
I don't know, if any of this is relevant, but maybe
I just updated Xcode to the latest version from the developer program (it supported up to iOS version 7.0 before, now 7.1)
I just started testing the app on an actual iPhone (I get the same problem testing with the simulator though)
Around the same time as this problem I also noticed that NSLog function doesn't work inside AppDelegate applicationHasLaunched method
Thanks
You didn't set the action for that button.
Change your createMyButton method like:
- (UIButton*) createMyButton
{
UIButton *button = [[UIButton alloc] init];
[button setTitle: #"My Button"
forState: UIControlStateNormal];
button.frame = CGRectMake(10, 10, 100, 40);
[button addTarget:self action:#selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
Also change myAction method like:
- (void)myAction:(UIButton *)sender
{
[sender performSelectorOnMainThread: #selector(removeFromSuperview) withObject: nil waitUntilDone: NO];
}
Your code seems overly complicated:
Why do you need to lazy create the button?
Why does it need to be readonly?
Why do you need the performselector in your action?
I have taken the liberty to rewrite your code:
Header file
#property (nonatomic,strong) UIButton * button;
Code file
- (void)viewDidLoad
{
[super viewDidLoad];
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
[self.button setTitle:#"MyButton" forState:UIControlStateNormal];
self.button.frame = self.view.bounds;
[self.button addTarget:self action:#selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.button];
}
-(void)myAction:(UIButton*)sender
{
[sender removeFromSuperview];
}
Happy coding!
Edit
If you insist on going with your original code, try changing
- (id) getMyButton
to
-(UIButton*)myButton
Buttons are a class family and should be created with [UIButton buttonWithType:]
I am sure that your myAction is not get fired. Cause you forget to addTarget
on your createMyButton method just add one more line
[button addTarget:self action:#selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
UPDATE: You've also marked this question as iOS but you are importing OSX headers
#import "NSViewController.h"
#interface MyViewController: NSViewController
you should be inheriting from UIViewController
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController
Are you creating the view controller via the init code you've posted?
- (id) init
{
if([super initWithNibName: nil bundle: nil])
{
_myButton = nil;
}
return self;
}
Here you are not allocating anything to self the code should be
- (id) init
{
self = [super initWithNibName: nil bundle: nil];
if(self)
{
_myButton = nil;
}
return self;
}

Adding addTarget: method to custom UIView

I created a custom UIView something like UIStepper, because I don't like the appearance of the UIStepper. I want UIStepper have a personal count label so I added it to my custom view and created a method to increase-decrease it. Now I need a [customView addTarget:(id) action:(del) forControlEvents:(UIControlEvents)] method to catch UIControlEventValueChanged; but I couldn't find anything about implementing it. I dig around the UIButton.h, UIStepper.h files but no luck too.. Can anyone help me to do that?
Here is how I created the custom view...
CounterView.h
#import <UIKit/UIKit.h>
#interface CounterView : UIView
#property NSString* name;
#property NSInteger count;
#property UILabel *label;
#property NSInteger customTag;
- (id)initWithX:(CGFloat)xPoint WithY:(CGFloat)yPoint WithName:(NSString*)newName withCount:(NSInteger)newCount withCustomTag:(NSInteger)newTag;
#end
CounterView.m
#implementation CounterView
- (id)initWithX:(CGFloat)xPoint WithY:(CGFloat)yPoint WithName:(NSString*)newName withCount:(NSInteger)newCount withCustomTag:(NSInteger)newTag
{
self = [super initWithFrame:CGRectMake(xPoint, yPoint, 24, 52)];
if (self) {
self.customTag = newTag;
self.count = newCount;
self.name = newName;
UIButton *btnUp = [[UIButton alloc] initWithFrame:CGRectMake(3, 2, 18, 12)];
[btnUp setImage:[UIImage imageNamed:#"top.png"] forState:UIControlStateNormal];
[btnUp addTarget:self action:#selector(increaseValue) forControlEvents:UIControlEventTouchUpInside];
UIButton *btnDown = [[UIButton alloc] initWithFrame:CGRectMake(3, 38, 18, 12)];
[btnDown setImage:[UIImage imageNamed:#"bottom.png"] forState:UIControlStateNormal];
[btnDown addTarget:self action:#selector(decreaseValue) forControlEvents:UIControlEventTouchUpInside];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, 24, 24)];
[self.label setText:[NSString stringWithFormat:#"%ld", (long)self.count]];
self.label.textAlignment = NSTextAlignmentCenter;
[self addSubview:btnUp];
[self addSubview:btnDown];
[self addSubview:self.label];
}
return self;
}
-(void) increaseValue{
self.count++;
[self.label setText:[NSString stringWithFormat:#"%ld", (long)self.count]];
}
-(void) decreaseValue{
self.count--;
[self.label setText:[NSString stringWithFormat:#"%ld", (long)self.count]];
}
#end
in the ViewController where you instantiate your CounterView you add this
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(handleSingleTap:)];
[yourViewInstantiation addGestureRecognizer:singleFingerTap];
[singleFingerTap release];
and the you implement the call back method:
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
CGPoint location = [recognizer locationInView:[recognizer.view superview]];
//Do stuff here...
}
i hope that help you !
Just allow the actions to be set from outside of your control. Here is how to do it:
#interface CounterView : UIView
...
#property(nonatomic, strong) UIButton *btnUp;
#property(nonatomic, strong) UIButton *btnDown;
- (void)addUpTarget:(id)target action:(SEL)action;
- (void)addDownTarget:(id)target action:(SEL)action;
#end
#implementation CounterView
...
- (void)addUpTarget:(id)target action:(SEL)action
{
[_btnUp addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}
- (void)addDownTarget:(id)target action:(SEL)action
{
[_btnDonw addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}
...
#end
Then use methods:
- (void)addUpTarget:(id)target action:(SEL)action;
- (void)addDonwTarget:(id)target action:(SEL)action;
to set a target and actions for increasing and decreasing the values.

selector as parameter in IOS

I want to raise a different method for each created button.
I try to call "FirstImage" method in viewDidLoad but it doesn't work.
I have a problem with the selector in ViewDidLoad. Didn't recognise "FirstImage" which is a void method without parameter.
ViewController.m
- (void)createFirstButton:(NSString *)myName: (SEL *)myAction{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn addTarget:self
action:#selector(myAction)
forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:myName forState:UIControlStateNormal];
btn.frame = CGRectMake(20, 916, 120, 68);
[self.view addSubview:btn];
}
- (void)viewDidLoad{
[self createFirstButton:#"First" myAction:[self FirstImage]];
}
What I have done (I changed "CreateFirstButton" into "CreateButton") :
ViewControler.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize myHeight;
#synthesize myWidth;
#synthesize myX;
#synthesize myY;
- (void)createButton:(NSString *)myName:(SEL)myAction:(NSUInteger)my_x:(NSUInteger)my_y:(NSUInteger)my_width:(NSUInteger)my_height
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn addTarget:self
action:myAction
forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:myName forState:UIControlStateNormal];
btn.frame = CGRectMake(my_x, my_y, my_width, my_height);
[self.view addSubview:btn];
}
- (void)myXcrementation{
myX = myX + 150;
}
- (void)viewDidLoad{
myX = 20; myY = 916; myWidth = 120; myHeight = 68;
[self createButton:#"First":#selector(FirstImage):myX:myY:myWidth:myHeight];
[self myXcrementation];
[self createButton:#"Previous":#selector(PreviousImage):myX:myY:myWidth:myHeight];
[self myXcrementation];
[self createButton:#"Pause":#selector(PauseImage):myX:myY:myWidth:myHeight];
[self myXcrementation];
[self createButton:#"Next":#selector(NextImage):myX:myY:myWidth:myHeight];
[self myXcrementation];
[self createButton:#"Last":#selector(LastImage):myX:myY:myWidth:myHeight];
}
- (void)FirstImage{
current = 0;
[self SetImage];
}
-(void)SetImage{
[myImageView setImage: [myArray objectAtIndex:(current)]];
}
#end
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
}
#property(assign, nonatomic) NSUInteger myHeight;
#property(assign, nonatomic) NSUInteger myWidth;
#property(assign, nonatomic) NSUInteger myX;
#property(assign, nonatomic) NSUInteger myY;
#end
I edited this post again and there is no more error.
Special thanks to everybody. It took me time to understand :)
You have to use use #selector as follows
[self createFirstButton:#"First" myAction:#selector(FirstImage)];
Then your signature is wrong, since SEL shouldn't be a pointer.
Change
- (void)createFirstButton:(NSString *)myName: (SEL *)myAction{
to
- (void)createFirstButton:(NSString *)myName: (SEL)myAction{
Finally myAction has type SEL so you can pass it directly to the UIButton method, as follows
[btn addTarget:self
action:myAction
forControlEvents:UIControlEventTouchUpInside];
Also, I'd like to add that using capitalized names for methods it's a very bad practice.
You should use
- (void)viewDidLoad{
[self createFirstButton:#"First" myAction:#selector(FirstImage)];
}
or
- (void)viewDidLoad{
[self createFirstButton:#"First" myAction:NSSelectorFromString(#"FirstImage")];
}
#selector(myAction) should be replaced with myAction, and (SEL *) should be replaced with SEL.
In your code, before -createFirstButton:myAction: is called, its second parameter [self FirstImage] would be evaluated(called) first. #selector() takes a name and returns a SEL.
Change the method literal as in the following
- (void)createFirstButton: (NSString *)myName withAction: (SEL)myAction
For both declaration and definition.
And also why have you declared the same method as a public as well as private?
Use
[self createFirstButton:#"First" withAction:NSSelectorFromString(#"FirstImage")];
And change the method name as :
- (void)createFirstButton:(NSString *)myName: withAction: (SEL) myAction{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn addTarget:self
action:myAction
forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:myName forState:UIControlStateNormal];
btn.frame = CGRectMake(20, 916, 120, 68);
[self.view addSubview:btn];
}
Also,
I wonder-all buttons having same frame, if possible pass frame this method.
If you are looking to pass string as method name to selector, then use NSSelectorFromString. String should end with ':' Example-
NSString *myName=#"aMethod:";
[button addTarget:self
action:NSSelectorFromString(myName)
forControlEvents:UIControlEventTouchDown];

Resources