以编程方式在UIButton上设置图像和文本 [英] Programmatically set image and text on UIButton

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

}

但是按钮上的文字没有显示。如果我为按钮注释 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.

Objective-C:

Objective-C:

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

Swift:

myButton.setBackgroundImage(buttonImage, forState: .normal)

这篇关于以编程方式在UIButton上设置图像和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆