0

我正在制作一个带有 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];
4

2 回答 2

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

于 2012-08-29T11:11:20.927 回答
0

当您设置图像时,它会覆盖标题。如果您可以将图像设置为背景图像,那将起作用。否则,您将需要通过本质上创建一个新图像来为按钮创建一个合成图像,该图像是您想要的图像,并在其上绘制了标题。

于 2012-08-29T11:13:39.100 回答