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


基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01