UIButton标签不可见

时间:2012-08-29 11:09:19

标签: ios uibutton

我正在制作一个带有2张图像的自定义UIButton,但由于某种原因标题没有显示,按钮显示正常,但没有任何标题。

_button = [UIButton buttonWithType:UIButtonTypeCustom];
_button.frame = CGRectMake(10, 250, 300, 43);
[_button addTarget:self action:@selector(loginClicked:) forControlEvents:UIControlEventTouchUpInside];
[_button setImage:[UIImage imageWithContentsOfFile:normalButtonImg] forState:UIControlStateNormal];
[_button setImage:[UIImage imageWithContentsOfFile:hoverButtonImg] forState:UIControlStateSelected];
[_button setTitle:@"Login" forState:UIControlStateNormal];
[_button setTitle:@"Login" forState:UIControlStateHighlighted];
[_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[self.view addSubview:_button];

2 个答案:

答案 0 :(得分:4)

这两行:

[_button setImage:[UIImage imageWithContentsOfFile:normalButtonImg] forState:UIControlStateNormal];
[_button setImage:[UIImage imageWithContentsOfFile:hoverButtonImg] forState:UIControlStateSelected];

应该是

[_button setBackgroundImage:[UIImage imageWithContentsOfFile:normalButtonImg] forState:UIControlStateNormal];
[_button setBackgroundImage:[UIImage imageWithContentsOfFile:hoverButtonImg] forState:UIControlStateSelected];

说明:如果为UIButton设置了前景图像,则图像位于标题上方,因此可能会隐藏它。如果您想要显示图片标题,则必须设置背景图片。

答案 1 :(得分:0)

设置图像时,会覆盖标题。如果你可以使你的图像成为背景图像,那将是有效的。否则,您将需要为按钮创建一个合成图像,实际上是创建一个新图像,该图像是您想要的图像,并在其上绘制标题。