Note that there are some explanatory texts on larger screens.

plurals
  1. POsetting custom UIButton style according to its state
    text
    copied!<p>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 :</p> <pre><code>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]; </code></pre> <p>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).</p> <p>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?</p> <p>Thank you!</p> <p><em>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.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload