此问题最常见的解决方法是"设为背景图片,而不是普通图片"
在我的情况下,我将背景图像放在我的所有按钮上,如果它是一个锁定的对象,我会在背景图像的顶部添加一个锁的图像。图像看起来像预期的那样,但在这种情况下,它不会显示图像的标题。
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];
}
这是没有锁定和锁定的图像:
答案 0 :(得分:5)
答案是here。
引用:"当您将图像放入按钮时,似乎是这样。文字被推到了右边。使用边缘设置将其重新带回图像。"
你要做的就是玩标题插图,以便将标题标签带回正确的位置。
我建议使用类似extraLeftInset
变量的内容,默认为0
,并在else
分支中设置为正确的值。
上面的答案建议使用此公式 [标题边缘插图]左= - (图像宽度* 2),因此该值应为-512,因为您说图像通常为256。在运行时评估图像的size
会更好。
希望这会有所帮助:)
答案 1 :(得分:0)
CGSize imageSize = button.imageView.image.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
0.0, - imageSize.width, 0.0, 0.0);
titleLabel的左侧底部填充。填充值必须等于图像宽度