5

I have a UIButton with title in the middle. I want to show images (icons) on left and right side of the button. On left side, its easy, I just set manually coordinates. But on the right side, I need the image to be moved along "x" axis, when display rotates and button is enlarged.

How to do this ?

Martin Perry
  • 9,232
  • 8
  • 46
  • 114

2 Answers2

9

Say you have a UIButton called button1, you can do something like this:

imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
imageView1.center = CGPointMake(25, button1.frame.size.height / 2);
imageView1.image = [UIImage imageNamed:@"ThumbsUp.png"];
[button1 addSubview:imageView1];
[imageView1 release];

imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
imageView2.center = CGPointMake(button1.frame.size.width - 25, button1.frame.size.height / 2);
imageView2.image = [UIImage imageNamed:@"ThumbsDown.png"];
[button1 addSubview:imageView2];
[imageView2 release];

Here we add two image views to the button and use their centers to position them. For imageView1, we set it 25 pixels from the left of the button. For imageView2, we subtract 25 from the button's width.

Now we have to set the rotation code:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation duration:(NSTimeInterval)duration {

    if (interfaceOrientation == UIDeviceOrientationPortrait || interfaceOrientation == UIDeviceOrientationPortraitUpsideDown) {
        [button1 setFrame:CGRectMake(10, 100, 300, 50)];
    } else {
        [button1 setFrame:CGRectMake(40, 50, 400, 50)];
    }
    imageView2.center = CGPointMake(button1.frame.size.width - 25, button1.frame.size.height / 2);
}

Here we change the button's frame depending on whether we're in portrait or landscape and last we set imageView2's center to adjust for the different frames. We don't have to bother with imageView1 as it stays the same.

jrturton
  • 118,105
  • 32
  • 252
  • 268
ShowMe Xcode
  • 136
  • 1
  • You're spoiling otherwise good answers by adding irrelevant links and signatures to the end. Please stop. – jrturton Sep 16 '12 at 10:41
  • What will happen when the text is too big to leave the necessary space on either sides? – geekay Sep 24 '12 at 10:18
  • First calculate the width of the button title using Stephen Poletto's answer [here](http://stackoverflow.com/questions/3429671/how-to-get-the-width-of-an-nsstring). Then, add the size.widths of the two UIImages and any additional padding you require. – Carl Smith May 28 '14 at 16:44
-1

You can also use this ReversedUIButton https://gist.github.com/fabnoe/bbf9545769d4a149faae

fabian
  • 5,433
  • 10
  • 61
  • 92