0

I try to make an horizontal navigation menu in scrollView. For every items in the menu i had a different image. When i select an item, i would like to change background image of this item, but i don't know why my code doesn't work:

for (int i=0; i<12; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            UIImage *normal=[UIImage imageNamed:@"icon1"];
            UIImage *selec=[UIImage imageNamed:@"icon1down"];
            [btn setFrame:CGRectMake(i*larg, 0, 42.0, 43.0)];
            [btn setBackgroundImage:normal forState:UIControlStateNormal];
            [btn setBackgroundImage:selec forState:UIControlStateSelected];

            [scrollCat addSubview:btn];
            cx+=42.0;
    }
    [scrollCat setContentSize:CGSizeMake(cx, 43)];

Is there a bad thing in this code?

Astram56
  • 536
  • 1
  • 7
  • 17

1 Answers1

0

Try UIControlStateHighlighted instead of UIControlStateSelected. Highlighted is the state when the user touches your button. Selected is only used for some controls, like segments ; a custom button (one that say, stays selected) would/could make use of Selected.

From the UIControl_Class docs at developer.apple.com (emphasis mine):

UIControlStateHighlighted

Highlighted state of a control. A control enters this state when a touch enters and exits during tracking and when there is a touch up event. ...

UIControlStateSelected

Selected state of a control. For many controls, this state has no effect on behavior or appearance. But other subclasses (for example, the UISegmentedControl class) may have different appearance depending on their selected state. ...

ckhan
  • 4,771
  • 24
  • 26
  • Thanks for your response, it works well but just when i click on an item. what about if i want the button stay with the second background image until i click on another item? – Astram56 May 26 '12 at 10:45
  • You can do both selected and highlighted. See http://stackoverflow.com/questions/1785008/keeping-a-uibutton-selected-after-a-touch – ckhan May 27 '12 at 07:43