问题描述
我需要以编程方式为正常和突出显示状态的图像以及文本创建按钮.我无法使用 Interface Builder 构建它,因为我需要在 UIScrollView
上创建按钮.这是我到目前为止的代码:
I need to create button programatically with an image for normal and highlighted state as well text. I cannot build it using Interface Builder, because I need to create buttons over a UIScrollView
. Here is the code I have so far:
- (void)loadView {
CGRect fullScreenRect=[[UIScreen mainScreen] applicationFrame];
scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect];
scrollView.contentSize=CGSizeMake(320,960);
UIImageView *tempImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.jpeg"]];
UIImage * buttonImage = [UIImage imageNamed:@"contentlist_active.png"];
self.view=scrollView;
[scrollView addSubview:tempImageView2];
btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(22, 100, 277, 32);
[btn setImage:buttonImage forState:UIControlStateNormal];
[btn setTitle:@"hello world" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[scrollView addSubview:btn];
}
但是按钮上的文字没有显示.如果我将 button
的 setImage
注释掉,那么文本会完美显示,否则不会.我可以同时拥有文字和图片吗?
But the text on the button is not showing. If I comment out the setImage
for button
, then text shows perfectly, otherwise not. Can I have both text and an image at the same time?
推荐答案
UIButtons setImage 将图像设置在标题上方,因此您将无法看到其下方的文本.因此,请尝试使用 setBackgroundImage 将图像设置为您的按钮.
UIButtons setImage sets the image above the title so you will not be able to see the text below it. So try to set image to your button with setBackgroundImage.
目标-C:
[btn setBackgroundImage:buttonImage forState:UIControlStateNormal];
斯威夫特:
myButton.setBackgroundImage(buttonImage, forState: .normal)
这篇关于以编程方式在 UIButton 上设置图像和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!