UIButton图像位置取决于titleLabel的框架

And*_*kha 3 objective-c uibutton uikit ios

我的问题很简单但我找不到解决方案.我有一个UIButton,它有一个标题和图像.无论发生什么事情我想要修复图像位置所以我这样设置:

[button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, IS_IPHONE ? 20.f : 60.f)];
Run Code Online (Sandbox Code Playgroud)

我没有为按钮设置任何位置titleLabel.

接下来发生的是我为按钮设置新标题,标题标签缩小或扩展以适应新文本,并且令人惊讶地使图像移动,因此很明显,尽管应用了图像边缘插入,但图像位置取决于标签的框架.我看到两种可以使用的解决方案:

1)使图像独立于标签的框架

2)为标签设置固定大小

但我不知道如何实现它们.能否请您给我一些建议如何解决这个问题?

Rah*_*ade 6

您可以子类化UIButton并管理图像和标题的rects.覆盖以下方法,并根据您的要求返回适当的图像和标题.

-(CGRect)imageRectForContentRect:(CGRect)contentRect;

-(CGRect)titleRectForContentRect:(CGRect)contentRect;
Run Code Online (Sandbox Code Playgroud)


Bar*_*uik 5

To fix this in Interface Builder, take the following steps.

First set the image and the text for the button. Then you'll want to create some space between the image and the button. This takes two steps: 1) Set the left content inset to, say, 10 points 2) Then set the image inset to minus 10 points

Step 1: 将内容嵌入左侧属性设置为10点

Step 2: 将图像嵌入左侧属性设置为负10点

Then to force the button to expand text to the right, only add a constraint to the left side:

添加顶部和左侧的约束

您不能只使用左侧插入标题的原因是因为这样您的标题将被截断:

在此输入图像描述

这是因为内部按钮大小调整不考虑标题和图像插入,仅使用内容插入.