UIButton with image left and right

I have a UIButton with a title in the middle. I want to show images (icons) to the left and right of the button. On the left side, simple, I just set the coordinates manually. But on the right side, I need the image to move along the x-axis when the display rotates and the button zooms in.

How to do it?

+4
source share
2 answers

Say your UIButton is 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 images to the button and use their centers to place them. For imageView1 we set it to 25 pixels to the left of the button. For imageView2, we subtract 25 from the width of the button.

Now we need 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 frame of the button depending on whether we are in a portrait or landscape, and for the last time we set the center of imageView2 to adjust for different frames. We do not need to worry with ImageView1 as it remains the same.

+8
source

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

-1
source

Source: https://habr.com/ru/post/1434224/


All Articles