详解iOS中UIButton的三大UIEdgeInsets属性用法

2020-01-15 14:02:22于丽

contentEdgeInsets里有一个content应该指的就是UIButton的title。

参数含义:

上面我们讲了UIEdgeInsets是个结构体类型。里面有四个参数,分别是:top, left, bottom, right。这四个参数表示距离上边界、左边界、下边界、右边界的距离。

这四个参数的值可以为正值,也可以为负值。拿left举例:


left = 10; //代表以当前位置为基准,向右移动10个像素
left = -10; //代表以当前位置为基准,向左移动10个像素

向右移动20个像素


button.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);

向右移动20个像素,left = 20,就可以了。

iOS,UIButton,UIEdgeInsets

向左移动20个像素


button.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);

iOS,UIButton,UIEdgeInsets

UIButton的titleEdgeInsets属性

titleEdgeInsets和contentEdgeInsets的作用差不多。我们及设置contentEdgeInsets,又设置titleEdgeInsets,会怎样呢?


button.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
button.contentEdgeInsets = UIEdgeInsetsMake(0, 20 , 0, 0);

看一下效果:

iOS,UIButton,UIEdgeInsets

UIButton的imageEdgeInsets属性

创建一个带照片的button:


UIButton *button = [[UIButton alloc] init];
button.frame = CGRectMake(50, 200, 200, 200);
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor orangeColor]];
[button setImage:[UIImage imageNamed:@"test"] forState:UIControlStateNormal];
[self.view addSubview:button];