2012-03-27 84 views
40

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

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

+0

你能告诉我如何对齐文本,左或右,如果我要放置阿拉伯文本为例。 – 2012-03-27 10:53:27

回答

76

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

的Objective-C:

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

斯威夫特:

myButton.setBackgroundImage(buttonImage, forState: UIControlState.Normal) 
+1

这样做,非常感谢:) – 2012-03-27 10:46:20

+0

你能告诉我如何对齐文本,无论是左或右,如果我要放置阿拉伯文字为例。 – 2012-03-27 10:52:49

+1

[yourButton.titleLabel setTextAlignment:UITextAlignmentLeft]; – iPrabu 2012-03-27 10:55:09

4

你试过

[btn setBackgroundImage:buttonImage forState:UIControlStateHighlighted]; 

它可能会解决你的问题。

+0

是的,它的工作,谢谢:) – 2012-03-27 10:50:36

22

你犯了一个错误在那里,你做

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

代替

[btn setImage:buttonImage forState:UIControlStateNormal]; 

这将正常工作。

+0

是啊我的不好,谢谢:) – 2012-03-27 10:54:04

0
 var menuButton:UIButton? 

    override func viewWillAppear(animated: Bool) { 
    menuButton = UIButton(frame: CGRectMake(0,0,30,30)) 
     menuButton?.setBackgroundImage(UIImage(named: "menu.png"), forState: UIControlState.Normal) 

    } 
相关问题