2012-03-27 83 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) 

    } 
相關問題