以编程方式在 UIButton 上设置图像和文本

2023-10-23移动开发问题
5

本文介绍了以编程方式在 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];

}

但是按钮上的文字没有显示.如果我将 buttonsetImage 注释掉,那么文本会完美显示,否则不会.我可以同时拥有文字和图片吗?

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 上设置图像和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

Cocos2d - 如何检查不同层中对象之间的交集
Cocos2d - How to check for Intersection between objects in different layers(Cocos2d - 如何检查不同层中对象之间的交集)...
2024-08-12 移动开发问题
8

恢复游戏 cocos2d
Resume game cocos2d(恢复游戏 cocos2d)...
2024-08-12 移动开发问题
6

突出显示朗读文本(在 iPhone 的故事书类型应用程序中)
Highlight Read-Along Text (in a storybook type app for iPhone)(突出显示朗读文本(在 iPhone 的故事书类型应用程序中))...
2024-08-12 移动开发问题
9

Cocos2D + 仅禁用 Retina iPad 图形
Cocos2D + Disabling only Retina iPad Graphics(Cocos2D + 仅禁用 Retina iPad 图形)...
2024-08-12 移动开发问题
10

正确的 cocos2d 场景重启?
Proper cocos2d scene restart?(正确的 cocos2d 场景重启?)...
2024-08-12 移动开发问题
7