2012-03-27 11 views
40

Necesito crear un botón programáticamente con una imagen para el estado normal y resaltado, así como el texto. No puedo construirlo usando Interface Builder, porque necesito crear botones sobre UIScrollView. Aquí está el código que tengo hasta ahora:Establecer imagen y texto mediante programación en 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]; 

} 

Pero el texto en el botón no se muestra. Si hago un comentario al setImage para button, entonces el texto muestra perfectamente, de lo contrario no. ¿Puedo tener texto y una imagen al mismo tiempo?

+0

¿Puede decirme cómo puedo alinear el texto, ya sea a la izquierda o a la derecha, si voy a colocar texto en árabe, por ejemplo. –

Respuesta

76

UIButtons setImage establece la imagen sobre el título para que no pueda ver el texto debajo de ella. Intenta configurar la imagen en tu botón con setBackgroundImage.

Objective-C:

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

Swift:

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

Eso lo hizo, muchas gracias :) –

+0

¿Puede decirme cómo puedo alinear el texto, ya sea a la izquierda o a la derecha, si voy a colocar el texto árabe, por ejemplo. –

+1

[yourButton.titleLabel setTextAlignment: UITextAlignmentLeft]; – iPrabu

4

Ha intentado

[btn setBackgroundImage:buttonImage forState:UIControlStateHighlighted]; 

Se podría resolver su problema.

+0

Sí funcionó, gracias :) –

22

Usted ha cometido un error ahí, que estás haciendo

[btn setBackgroundImage:buttonImage forState:UIControlStateNormal]; 

en lugar de

[btn setImage:buttonImage forState:UIControlStateNormal]; 

Esto funcionará bien.

+0

sí, mi mal, gracias :) –

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) 

    } 
Cuestiones relacionadas