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

这两行:

[_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设置了前景图像,则该图像会放置在标题上方,因此可能会将其隐藏。如果要显示图像标题,则必须设置背景图像。

设置图像时,会覆盖标题。如果你能让你的图像成为背景图像,那就行了。否则,您将需要为按钮创建一个合成图像,基本上创建一个新图像,这是您想要的图像,并在其上绘制标题。

最新更新