Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 482
Martin Perry Avatar asked Sep 14 '12 14:09

Martin Perry


People also ask

How do I put the image on the right side of the text in a UIButton?

To make an UIButton's image align to the right side of the text, we force content flipping behavior to the one use it right-to-left language. 1 By adding this semanticContentAttribute = . forceRightToLeft , we force UIKit to mirrored our content which push our image to the right side of the text.

What is Uiimage?

An object that manages image data in your app.

What is a UIButton?

A control that executes your custom code in response to user interactions.


1 Answers

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.

like image 185
ShowMe Xcode Avatar answered Sep 30 '22 11:09

ShowMe Xcode