2012-03-27 16 views
40

Devo creare il pulsante in modo programmatico con un'immagine per lo stato normale e evidenziato come pure il testo. Non riesco a costruirlo utilizzando Interface Builder, perché ho bisogno di creare pulsanti su un UIScrollView. Ecco il codice che ho finora:Impostazione di immagine e testo su 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]; 

} 

Ma il testo sul pulsante non viene visualizzato. Se commento il setImage per button, il testo mostra perfettamente, altrimenti no. Posso avere sia il testo sia un'immagine allo stesso tempo?

+0

Potete dirmi come posso allineare il testo, a sinistra oa destra, se devo inserire un testo arabo per esempio. –

risposta

76

UIButtons setImage imposta l'immagine sopra il titolo in modo da non essere in grado di vedere il testo sottostante. Quindi prova a impostare l'immagine sul tuo pulsante con setBackgroundImage.

Objective-C:

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

Swift:

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

Ciò ha funzionato, grazie mille :) –

+0

Puoi dirmi come posso allineare il testo, a sinistra oa destra, se devo inserire un testo arabo, ad esempio. –

+1

[yourButton.titleLabel setTextAlignment: UITextAlignmentLeft]; – iPrabu

4

Hai provato

[btn setBackgroundImage:buttonImage forState:UIControlStateHighlighted]; 

Potrebbe risolvere il problema.

+0

Sì, ha funzionato, grazie :) –

22

Hai fatto un errore lì, si sta facendo

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

invece di

[btn setImage:buttonImage forState:UIControlStateNormal]; 

Questo funziona bene.

+0

sì mio male, grazie :) –

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) 

    } 
Problemi correlati