views:

62

answers:

1

Hi friends,

I have created scroll view and sets the buttons are in the scroll view. The Buttons are scrolling horizontally and it works fine. If i clicked the button, i set background image as "Selected State" in button. My problem is how can i changed the selected state in different button, when clicking it and how can i deselected the "selected state" button when clicking the another button.

I have three buttons in the scroll view,

 -(IBAction) Button1 : (id) sender
 {  
    // btn1.selected = YES;
          [btn1 setImage:[UIImage imageNamed:@"first.png"]  forState:UIControlStateSelected];

 }

 -(IBAction) Button2 : (id) sender
 {  
    // btn2.selected = YES;
        [btn2 setImage:[UIImage imageNamed:@"second.png"]  forState:UIControlStateSelected];

 }

 -(IBAction) Button3 : (id) sender
 {
   // btn3.selected = YES;
       [btn3 setImage:[UIImage imageNamed:@"three.png"]  forState:UIControlStateSelected];

 }

see the below image,(Health, Entertainment and Money Watch are the three buttons)

Image

and

Img

Note:(Like, Tabbar and Segmented control)

On clicking first button and sets background image in selected state and clicking the second button, then first buttons are to be deselected. So how can i maintain the selected state, till another button is clicked.

Thanks in Advance.

+2  A: 

I solved this task in the following way:

init method:

  • Create number of buttons with defined images for normal and selected state.
  • Assign tag for each button (for example, for i'th button tag is 1000+i).
  • Assign IBAction for each button.

action method:

  • Remove selection from previously selected button (search it by it's tag with [view viewWithTag:] method)
  • Select sender.
  • Save sender's tag.

Here's the code:

- (void)init {

....INITIALIZE SCROLLVIEW HERE.....

    for ( int i = 0; i < 10; i++ ) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

        [btn setFrame:.....];
        [btn setImage:_IMAGE_ forState:UIControlStateNormal];
        [btn setImage:_IMAGE2_ forState:UIControlStateSelected];
        [btn setTag:i + 1000];

        [btn addTarget:self action:@selector(setSelectedButton:) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:btn];
    }
}

- (IBAction)setSelectedButton:(id)sender {
    [self setSelectedButtonByIndex:((UIButton *)sender).tag - 1000];
}

- (void)setSelectedButtonByIndex:(NSInteger)index {
    if ( selectedElemId >= 0 ) {
        UIButton *btn = (UIButton *)[self viewWithTag:selectedElemId + 1000];
        [btn setSelected:NO];
    }

    UIButton *btn = (UIButton *)[self viewWithTag:index + 1000];
    [btn setSelected:YES];

    selectedElemId = btn.tag - 1000;
}
kovpas
+1, kovpas, Thanks for Your detailed answer. It works fine. Thanks a lot...
Pugal Devan