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

我的问题很简单,但我找不到解决scheme。 我有一个标题和图像的UIButton。 无论发生什么事情,我都希望图像位置得到修复,所以我这样设置:

[button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, IS_IPHONE ? 20.f : 60.f)]; 

我没有为button的titleLabel设置任何位置。

接下来发生的事情是我为button设置了新的标题,标题标签缩小或展开以适应新的文本,令人惊讶的是它使图像移动,所以很明显,尽pipe应用了图像边缘插入,图像位置取决于标签的框架。 我看到两个可以使用的解决scheme:

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

2)为标签设置固定大小

但是我不知道如何实现它们。 你能给我一些build议,我该如何解决这个问题?

你可以inheritanceUIButton并pipe理图像和标题的rects。 重写下面的方法,并根据您的要求返回图像和标题的适当rect。

 -(CGRect)imageRectForContentRect:(CGRect)contentRect; -(CGRect)titleRectForContentRect:(CGRect)contentRect; 

要在Interface Builder中解决这个问题,请执行以下步骤。

首先设置button的图像和文字。 那么你会想在图像和button之间创build一些空间。 这需要两个步骤:1)将左侧的内容插入到10点2)然后将图像设置为负10点

步骤1: 将左侧属性的内容设置为10分

第2步: 将图像的左侧属性设置为负10点

然后强制button向右扩展文本,只在左侧添加一个约束:

为顶部和左侧添加约束

原因是你不能只使用标题左插入,是因为你的标题将被截断:

在这里输入图像说明

这是因为标题和图像插入不考虑内在button大小,只使用内容插入。

这是因为设置了UIButton的图像插入和标题插入。 你可以尝试一下@mehul patel给出的build议,@Nirav BHatt和@这个家伙。

或者你可以尝试这种方式:在这里我们假设你的图像是第一个,然后titleLabelbutton。

  //-------- Create button --------- UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(50, 100, 100, 40)]; btn.backgroundColor = [UIColor cyanColor]; //----- Create imageview -------- UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 20, 20)]; imgView.image = [UIImage imageNamed:@"your_image_name.png"]; //----- Create Name label ----------- UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(imgView.frame.origin.x+imgView.frame.size.width+10, 0, 80, btn.frame.size.height)]; nameLabel.backgroundColor = [UIColor blueColor]; nameLabel.textAlignment = NSTextAlignmentLeft; nameLabel.textColor = [UIColor whiteColor]; nameLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:14]; nameLabel.text = @"your title label"; nameLabel.adjustsFontSizeToFitWidth = YES; [nameLabel sizeToFit]; //-------- Resize button frame ---------- btn.frame = CGRectMake(btn.frame.origin.x, btn.frame.origin.y, nameLabel.frame.origin.x+nameLabel.frame.size.width+10, btn.frame.size.height); [btn addSubview:nameLabel]; [btn addSubview:imgView]; 

你可以添加图像和标签反之亦然(第一个标签,然后图像),然后根据它更新button的框架。