【问题标题】:UIButton image position depends on the frame of titleLabelUIButton 图像位置取决于 titleLabel 的框架
【发布时间】:2014-09-25 10:26:24
【问题描述】:

我的问题很简单,但我找不到解决方案。我有一个具有标题和图像的 UIButton。无论发生什么,我都希望图像位置固定,所以我这样设置:

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

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

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

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

2) 为标签设置固定大小

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

【问题讨论】:

  • UIButton的标题标签文字可以得到CGSize,然后增加UIButton的宽度。
  • 你可能想看看这个:stackoverflow.com/q/4564621/1506363
  • 按照@NiravBhatt 的建议,也尝试设置标题的插图。

标签: ios objective-c uibutton uikit


【解决方案1】:

您可以继承 UIButton 并管理图像和标题的矩形。 覆盖以下方法并根据您的要求为图像和标题返回适当的矩形。

-(CGRect)imageRectForContentRect:(CGRect)contentRect;

-(CGRect)titleRectForContentRect:(CGRect)contentRect;

【讨论】:

    【解决方案2】:

    这是因为设置了 UIButton 的 image inset 和 title inset。 您可以尝试@mehul patel、@Nirav BHatt 和@The dude 给出的上述建议。

    或者你可以试试这个方法:这里我们假设你的图片是第一个,然后是按钮中的titleLabel。

     //-------- 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];
    

    您可以添加图像和标签,反之亦然(先是标签,然后是图像),然后根据它更新按钮的框架。

    【讨论】:

      【解决方案3】:

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

      首先设置按钮的图像和文本。然后,您需要在图像和按钮之间创建一些空间。这需要两个步骤: 1) 将左边的内容插图设置为 10 点 2)然后将图像插图设置为负10分

      第 1 步:

      第 2 步:

      然后强制按钮向右展开文本,只在左侧加一个约束:

      你不能只使用左边插入的标题,因为这样你的标题会被截断:

      这是因为内部按钮大小没有考虑标题和图片插图,只使用了内容插图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多