Martin Perry Martin Perry - 1 year ago 122
Objective-C Question

UIButton with image on left and right side

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 ?

Answer Source

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

imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; = 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)]; = 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)];
    } = 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download