I made a simple app in which i am loading different .xib
on each orientation,
I have two xib's Portxib
and Landxib
, in both xibs, i dragged a button and assigned a
tag 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
Make sure...
xib
as you are finding it in self.view
OR make sure it is placed in correct view and use that view with viewWithTag
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.
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With