I am creating a custom UIButton in my program (not in IB) and I would like it to show different images on different states, so I did :
UIImage *learnImg=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"01" ofType:@"png"]];
self.learn=[[UIButton buttonWithType:UIButtonTypeCustom] retain];
[self.learn setFrame:CGRectMake(148, 108,254,97)];
[[self.learn imageView] setContentMode:UIViewContentModeScaleAspectFit];
[self.learn setImage:learnImg forState:UIControlStateNormal];
UIImage *learnSelected=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"02" ofType:@"png"]];
[self.learn setImage:learnSelected forState:UIControlEventTouchDown];
[self.learn addTarget:self action:@selector(loadLearn:) forControlEvents:UIControlEventTouchUpInside];
The problem is, the two images have different sizes so when I click on the button, the position of the button got ‘translated’ (I believe this is due to the ‘setFrame’ behaviour since the xy location should be relative).
I couldn’t think of a way to fix this, all I want is to make sure the button is right at the position during whatever states it’s in. Is there anyway that I can set a complete set of style for each button state (frame, images etc)? Or any other thoughts?
Thank you!
I finally worked this around by re-setting the center of the button through two action events: UIControlEventTouchDown and UIControlEventTouchCancel.
Thanks all for the comments.
UIControlEventTouchDownis not a state of the button. Its an event registered by the button. The various states for theUIButtonare