I had an application in which I am adding some dynamic number of buttons to a scrollview. I had set a normal background and selected background for the UIButton
. For some reasons I need to call the UIButton
sender method programmatically by:
[self buttontapped:nil];
as this but it is not changing the background of the button by using the code:
button.selected = YES;
I had set the background like this initially of the button:
btn = [UIButton buttonWithType:UIButtonTypeCustom];
int j = i+1;
btn.frame = CGRectMake((j-1)*77, 0, 77, 44);
[btn setBackgroundImage:[UIImage imageNamed:@"bar.png"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:@"bar_hvr.png"] forState:UIControlStateSelected];
btn.selected = NO;
btn.backgroundColor = [UIColor clearColor];
btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
btn.titleLabel.textColor = [UIColor whiteColor];
[btn setTitle:head forState:UIControlStateNormal];
btn.tag = i;
[tabBarS addSubview:btn];
-(void)buttonTapped:(id)sender {
if(sender==nil)
{
btn.tag=0;
}
for(int i=0;i<[sarray count];i++)
{
btn.selected=NO;
}
btn = (UIButton *)sender;
NSLog(@"Tab bar %d is clicked",btn.tag);
[self tabCall:btn.tag];
btn.selected = YES;
}
But everything except change of background only working. Where am I going wrong?
i done with bellow method call your UIButton method like:-
btn= [UIButton buttonWithType:UIButtonTypeCustom];
int j=i+1;
btn.frame = CGRectMake((j-1)*77, 0, 77, 44);
[btn setBackgroundImage:[UIImage imageNamed:@"bar.png"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:@"bar_hvr.png"] forState:UIControlStateSelected];
btn.selected=NO;
[btn addTarget:self action:@selector(yourButtonAction:) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor = [UIColor clearColor];
btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
btn.titleLabel.textColor = [UIColor whiteColor];
btn.tag = i;
[tabBarS addSubview:btn];
and it's Action Method should like with sender
-(IBAction)yourButtonAction:(id)sender
{
UIButton *btn = (UIButton*)sender;
if (![btn isSelected])
{
[btn setImage:[UIImage imageNamed:@"selected_fb_btn.png"] forState:UIControlStateNormal];
[btn setSelected:YES];
[self login];
}
else{
[btn setImage:[UIImage imageNamed:@"facebook.png"] forState:UIControlStateNormal];
[btn setSelected:NO];
}
}
EDIT
You can call button action event programeticuly using bellow trik:-
[btn sendActionsForControlEvents:UIControlEventTouchUpInside];