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

标签 ios iphone ios4 xcode4.2

我需要以编程方式创建按钮,其中包含用于正常和突出显示状态以及文本的图像。我无法使用 Interface Builder 构建它,因为我需要在 UIScrollView 上创建按钮。这是我到目前为止的代码:

- (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,那么文本会完美显示,否则不会。我可以同时拥有文字和图片吗?

最佳答案

UIButtons setImage 将图像设置在标题上方,因此您将无法看到其下方的文本。 因此,请尝试使用 setBackgroundImage 将图像设置为您的按钮。

objective-C :

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

swift :

myButton.setBackgroundImage(buttonImage, forState: .normal)

关于ios - 以编程方式在 UIButton 上设置图像和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9887959/

相关文章:

iphone - Cocoa Touch 是否有与 Adob​​e Flex 的 HBox 或 VBox 等效的 UIView 或组件?

iphone - 即使使用 setNeedsDisplay 和 setNeedsLayout 自定义 UITableViewCell 也不会更新

ios - 键盘覆盖了我 View 底部的文本字段

ios - Swift for循环嵌套数组性能

iphone - 在 map View 中使用 CLGeocoder 而不是私有(private) API

ios - 如何同时滑入/滑出状态栏和导航栏?

iOS - 当两个网络(WIFI 和 CELL)都可用时如何识别使用哪个网络

iphone - Apple 批准的加密应用程序

ios - 在整个应用程序中禁用 UITextField 的自动更正

ios - android上axios发布请求网络错误