问题描述
我需要以编程方式为正常和突出显示状态的图像以及文本创建按钮.我无法使用 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 上设置图像和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)