我在setImage时没有显示UIButton标题

Esq*_*uth 1 uibutton ios

此问题最常见的解决方法是"设置为背景图像,而不是普通图像"

在我的情况下,我将背景图像放在我的所有按钮上,如果它是一个锁定的对象,我会在背景图像的顶部添加一个锁的图像.图像看起来像预期的那样,但在这种情况下它不显示图像的标题.

UIButton *button = (UIButton *)view;
if(self.currentArray[index][2] != NULL) //before it was if (button == nil)
{
    NSString *name = [[NSString alloc] initWithString:self.currentArray[index][2]];
    UIImage *image = [UIImage imageNamed:self.currentArray[index][5]];
    button = [UIButton buttonWithType:UIButtonTypeCustom];

    if ([self.currentArray[index][6] isEqualToString:@"true"]) {
        //show it
    }else{
//-------------------------        
//--THE PROBLEM HAPPENS IF THIS PIECE OF CODE IS EXECUTED, SPECIFICALLY setImage
//------------------------- 
        button.alpha = 0.5;
        UIImage *locked = [UIImage imageNamed:@"locked.png"];
        button.imageEdgeInsets = UIEdgeInsetsMake(15, 15, 15, 15);
        [button setImage:locked forState:UIControlStateNormal];
    }

    button.frame = CGRectMake(0.0, 0.0, 56, 56);
    button.tag = index;

    [button setBackgroundImage:image forState:UIControlStateNormal];

    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIEdgeInsets buttonInset = UIEdgeInsetsMake(30, -30, -25, -30);
    [button setTitleEdgeInsets:buttonInset];
    [button setTitle:name forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize: 8];

    [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
}
Run Code Online (Sandbox Code Playgroud)

这是没有锁和锁的图像:
在此输入图像描述

mok*_*gio 5

答案就在这里.

引用:"看起来当您将图像放入按钮时.文本被推向右侧.使用边缘设置将其重新带回图像."

你要做的就是玩标题插图,以便将标题标签带回正确的位置.

我建议有一个像extraLeftInset默认的变量,0并在else分支中设置为正确的值.

上面的答案建议使用这个公式[Edge inset for Title] Left = - (imageWidth*2),所以值应该是-512,因为你说图像通常是256.在运行时检查它会更好在size虽然形象.

希望这可以帮助 :)