UIButton的titleEdgeInsets毫无意义

时间:2016-11-18 00:52:57

标签: ios swift uibutton

我有一张UIButton的图片和标题。我正试图让我的图像(宽度为15像素)左对齐,我的标题要对齐5px左右:

Button Example

按钮的宽度为215,但我必须将我的titleEdgeInset设置为-44。这没有意义。什么数学得到-44?

3 个答案:

答案 0 :(得分:3)

这是因为按钮的图像和标题默认居中在一起。

例如,这里有一个300px宽的按钮,带有图像和文字,没有插图:

Default button spacing

看起来我需要将按钮内容向左移动60分,所以-60左边插入,右边60插入。

button.imageEdgeInsets = UIEdgeInsetsMake(0.0, -60.0, 0.0, 60.0)
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -60.0, 0.0, 60.0)

enter image description here

修改

这些插图也可用于上述示例。

button.imageEdgeInsets = UIEdgeInsetsMake(0.0, -120.0, 0.0, 0.0)
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -120.0, 0.0, 0.0)

按钮正在对其内容进行居中,所以如果你说"左边还有2个点"按钮将其内容移动1 pt以使它们居中。

规则是

<强> -leftInset + rightInset = LEFTMARGIN * 2

答案 1 :(得分:0)

很容易做到:

在swift3中:

let button: UIButton = UIButton.init(frame: CGRect.init(x: 44, y: 64, width: 100, height: 40))

    button.backgroundColor = UIColor.clear
    button.setImage(UIImage.init(named: "img"), for: UIControlState.normal)
    button.setTitle("hello", for: UIControlState.normal)
    button.layer.borderWidth = 1
    button.layer.borderColor = UIColor.blue.cgColor
    button.layer.cornerRadius = 4

    // set edge inset
    button.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -40, bottom: 0, right: 0)
    button.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -20, bottom: 0, right: 0)

    self.view.addSubview(button)

在objective-c:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(44, 64, 100, 40);
    button.backgroundColor = [UIColor clearColor];
    [button setImage:[UIImage imageNamed:@"img"] forState:UIControlStateNormal];
    [button setTitle:@"hello" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    button.layer.cornerRadius = 4;
    button.layer.borderColor = [UIColor blueColor].CGColor;
    button.layer.borderWidth = 1;
    // set edge inset
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -40, 0, 0);
    button.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [self.view  addSubview:button];

The result

答案 2 :(得分:0)

默认情况下,UIButton与其他答案一样,处于居中状态,但是您可以更改它以实现更直观的插入行为。 在属性检查器中选择左对齐。

enter image description here

然后像这样设置插图:

button.imageEdgeInsets = UIEdgeInsets.zero
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)