Original Address :: https://www.jianshu.com/p/65d559614efc
According to demand, sometimes you need to button
add pictures and text, which requires the use button
of titleEdgeInsets
and imageEdgeInsets
properties. With a good, but at the same time using these two control feel bad, a lot of time title
in the picture below but not centered. The long-troubled, we study a little today, to sum up.
UIEdgeInsets
typedef struct UIEdgeInsets {
CGFloat top, left, bottom, right; // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;
Inside the four parameter represents the distance from the boundary, left boundary, the lower boundary, the right boundary, the default are zero, title / image in the center of the button
First on the code, using the pixel image is 55 * 55
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.backgroundColor = [UIColor orangeColor];
btn.frame = CGRectMake(100, 100, 80, 80);
[btn setImage:[UIImage imageNamed:@"致电我们-图标"] forState:0];
[btn setTitle:@"1234" forState:0];
[btn setTitleColor:[UIColor whiteColor] forState:0];
[btn setImageEdgeInsets:UIEdgeInsetsMake(5, 25, 45, 25)];
[btn setTitleEdgeInsets:UIEdgeInsetsMake(50, 0, 5, 0)];
[self.view addSubview:btn];
Defines a btn, I thought I could show the correct button, run to see I was wrong. Text not show up.
9E93E830-8405-473C-A364-E7397DA5D971.png
After repeated testing, we found set
[btn setTitleEdgeInsets:UIEdgeInsetsMake(50, -55, 5, 0)];
Just to make the text centered and displayed; But again, the picture becomes a pixel, and ran the rest of the text to go. So explore the ultimate solution: to set the text under the picture, and then set the picture (provided that the image pixels than the button
pixels smaller, you still have to press the picture is really pixels)
[btn setTitleEdgeInsets:UIEdgeInsetsMake(50, -btn.imageView.bounds.size.width, 5, 0)];
[btn setImageEdgeInsets:UIEdgeInsetsMake(5, 25, 45, 25)];
200C4F64-A9CE-402B-90DB-3652DC6D78FD.png
Similarly, if the left and right images and text display
Directly on the code
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
btn1.backgroundColor = [UIColor orangeColor];
btn1.frame = CGRectMake(100, 250, 100, 60);
[btn1 setImage:[UIImage imageNamed:@"致电我们-图标"] forState:0];
[btn1 setTitle:@"电话" forState:0];
[btn1 setTitleColor:[UIColor whiteColor] forState:0];
[btn1 setTitleEdgeInsets:UIEdgeInsetsMake(15, -btn1.imageView.bounds.size.width + 40, 15, 0)];
[btn1 setImageEdgeInsets:UIEdgeInsetsMake(10, 5, 10, 55)]; //40 * 40
[self.view addSubview:btn1];
display
7AB616A1-1BB8-4CB2-BC5A-3FD59A7B16A4.png
to sum up
In short, the set button
when these two properties, the real picture about the pixel. If more than one button
, it is best to ensure that the picture pixel is the same.