Click event of UIButton is not getting fired
Solution 1
Make sure...
- Button is placed in root view in
xib
as you are finding it inself.view
OR make sure it is placed in correct view and use that view withviewWithTag
- You have assigned tag 1, so just make sure no other control within same view have tag 1 other wise button will not be recognized by tag. If this is going to be your case then just change tag of button to very unusual number for that view like 999 or any thing else and test.
EDIT
I am feeling like you view is not getting recognized at viewDidLoad
where you have setup your code. So just comment out that code in viewDidLoad
and shift in your changeOrientation method after loading nib.
-(void)changeOrientation
{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if(orientation==UIInterfaceOrientationPortrait || orientation==UIInterfaceOrientationPortraitUpsideDown)
{
[[NSBundle mainBundle] loadNibNamed:@"PortraitXib" owner:self options:nil];
}
else
{
[[NSBundle mainBundle] loadNibNamed:@"LandscapeXib" owner:self options:nil];
}
//Adding this code here makes sense that nib is loaded and after that we are recognizing button from loaded view of nib.
UIButton *btn = (UIButton*)[self.view viewWithTag:1];
[btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
Hope this helps.
Solution 2
In header file add
IBOutlet UIButton *btn;
reference this btn from your xib files.
Here in your case the btn you are using is not referenced from the xib files so the method is not firing
-(IBAction)BtnClick:(id)sender
{
NSLog(@"BtnClick");
}
make the function as IBAction and reference this from nib btn. In this case you no need to addtarget explicitly.
If you are not adding the button in the nib, then dont forget to init and addsubview to the view
You can see this tutorial http://www.idev101.com/learn/interface_builder_connections.html
EDIT Check what is printing?
for (UIButton *but in [self.view subviews])
{
NSLog("but.tag %d",but.tag);
if(but.tag==1)// compare for same row elements
{
NSLog("Button Added");
[btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
}
Krunal
iPhone/iPad developer from Mumbai (India) and you will always find me here to help you ;)
Updated on June 04, 2022Comments
-
Krunal almost 2 years
I made a simple app in which i am loading different
.xib
on each orientation,I have two xib's
Portxib
andLandxib
, in both xibs, i dragged a button and assigned atag value to it as
1
in both xib's.and i wrote this code in my
viewDidLoad
UIButton *btn=(UIButton *)[self.view viewWithTag:1]; [btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
here is the selector method,
-(void)BtnClick:(id)sender { NSLog(@"BtnClick"); }
Click event of UIButton is not getting fired...
OR
Is there any other way to call the same method of button from both the orientation ??
EDIT :
.h file
.m file