2009-09-24 7 views
169

Come si imposta l'immagine per un UIButton nel codice?Impostazione di un'immagine per un UIButton nel codice

ho questo:

UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btnTwo.frame = CGRectMake(40, 140, 240, 30); 
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal]; 
[btnTwo addTarget:self action:@selector(goToOne) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:btnTwo]; 

ma non vedo cosa impostare l'immagine per esso.

risposta

350

Objective-C

UIImage *btnImage = [UIImage imageNamed:@"image.png"]; 
[btnTwo setImage:btnImage forState:UIControlStateNormal]; 

Swift

let btnImage = UIImage(named: "image") 
btnTwo.setImage(btnImage , forState: UIControlState.Normal) 
+1

Come un sidenote: questo mostrerà l'immagine, ma il testo del titolo del pulsante sarà nascosto. – leviathan

+0

Questo è il codice è completamente funzionante, ma sto ottenendo l'immagine con l'analisi, quindi come posso fare questo come questo codice è lavorato per me in caso UIImage: - largePick.image = aNewsInfo.smallImageData; come posso fare questo con UIButton ... Puoi aiutarmi ... – user755278

+1

@slcott, dove [la documentazione] (http://developer.apple.com/library/ios/#documentation/UIKit/ Riferimento/UIButton_Class/UIButton/UIButton.html) lo dichiari? Non vedo suggerire da nessuna parte che 'setImage' sia deprecato. (Mi sembra che tu stia confondendo 'UIButton.setImage' con' UITableViewCell.image', che * è * una proprietà deprecata come hai affermato.) –

56

soluzione di Mike sarà solo mostrare l'immagine, ma qualsiasi titolo impostato sul pulsante non sarà visibile, in quanto è possibile impostare il titolo o l'immagine.

Se si desidera impostare entrambi (la vostra immagine e titolo) utilizzare il seguente codice:

btnImage = [UIImage imageNamed:@"image.png"]; 
[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal]; 
[btnTwo setTitle:@"Title" forState:UIControlStateNormal]; 
+2

qual è la differenza tra ** setImage ** e ** setBackgroundImage **? – onmyway133

+3

setBackgroundImage estenderà l'immagine sulla larghezza del pulsante sul testo del titolo mentre setImage renderà il pulsante un'immagine ignorando il testo del titolo senza allungare l'immagine. – Ernest

8

È possibile inserire l'immagine in uno dei modo:

UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btnTwo.frame = CGRectMake(40, 140, 240, 30); 
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal]; 
[btnTwo addTarget:self 
      action:@selector(goToOne) 
forControlEvents:UIControlEventTouchUpInside]; 


[btnTwo setImage:[UIImage imageNamed:@"name.png"] forState:UIControlStateNormal]; 

//OR setting as background image 

[btnTwo setBackgroundImage:[UIImage imageNamed:@"name.png"] 
        forState:UIControlStateNormal]; 

[self.view addSubview:btnTwo]; 
+0

Questa parte del codice mi ha confuso. btnImage = [UIImage imageNamed:@"image.png"]; Qual è btnImage? Quello non era nel codice originale. È un nuovo pulsante? –

+0

puoi impostare direttamente l'immagine del pulsante invece di prendere un altro oggetto immagine come questo: [btnTwo setImage: [UIImage imageNamed: @ "image.png"]]; –

+0

devi avere buttonWithType: UIButtonTypeRoundedRect to UIButtonTypeUn altro pulsante saggio non verrà visualizzato come per l'immagine. –

21

Prima di questo dovrebbe funzionare per me ho dovuto ridimensionare la cornice del pulsante in modo esplicito in base alla dimensione della cornice dell'immagine.

UIImage *listImage = [UIImage imageNamed:@"list_icon.png"]; 
UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom]; 

// get the image size and apply it to the button frame 
CGRect listButtonFrame = listButton.frame; 
listButtonFrame.size = listImage.size; 
listButton.frame = listButtonFrame; 

[listButton setImage:listImage forState:UIControlStateNormal]; 
[listButton addTarget:self.navigationController.parentViewController 
       action:@selector(revealToggle:) 
    forControlEvents:UIControlEventTouchUpInside]; 
UIBarButtonItem *jobsButton = 
    [[UIBarButtonItem alloc] initWithCustomView:listButton]; 

self.navigationItem.leftBarButtonItem = jobsButton; 
+0

Questo trucco per ridimensionare i pulsanti è molto utile. –

+0

@jrasmusson voleva solo aggiungere che le 3 linee di manipolazione con il frame possono anche essere scritte in '[listButton sizeToFit]' – bk138

9

Si può fare in questo modo

[btnTwo setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal]; 
9
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
btn.frame = CGRectMake(0, 0, 150, 44); 
[btn setBackgroundImage:[UIImage imageNamed:@"buttonimage.png"] 
       forState:UIControlStateNormal]; 
[btn addTarget:self 
    action:@selector(btnSendComment_pressed:) 
    forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:btn]; 
2

ero alla ricerca di una soluzione per aggiungere un UIImage al mio UIButton. Il problema era che mostra l'immagine più grande del necessario. Basta che mi ha aiutato con questo:

_imageViewBackground = [[UIImageView alloc] initWithFrame:rectImageView]; 
_imageViewBackground.image = [UIImage imageNamed:@"gradientBackgroundPlain"]; 
[self addSubview:_imageViewBackground]; 
[self insertSubview:_imageViewBackground belowSubview:self.label]; 
_imageViewBackground.hidden = YES; 

Ogni volta che voglio mostrare il mio UIImageView ho appena impostato il var hidden-YES o NO. Potrebbero esserci altre soluzioni ma mi sono confuso così tante volte con questa roba e questo l'ho risolto e non avevo bisogno di occuparmi di roba interna UIButton in background.

8

In caso di Swift utente

// case of normal image 
let image1 = UIImage(named: "your_image_file_name_without_extension")! 
button1.setImage(image1, forState: UIControlState.Normal) 

// in case you don't want image to change when "clicked", you can leave code below 
// case of when button is clicked 
let image2 = UIImage(named: "image_clicked")! 
button1.setImage(image2, forState: UIControlState.Highlight) 
2

Non ti preoccupare tanto che incornicia il pulsante dal codice, si può fare sullo storyboard. Questo ha funzionato per me, una riga ... più semplice.

[self.button setBackgroundImage:[UIImage imageNamed: @"yourPic.png"] forState:UIControlStateNormal]; 
1
-(void)buttonTouched:(id)sender 
{ 
    UIButton *btn = (UIButton *)sender; 

    if([[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"icon-Locked.png"]]) 
    { 
     [btn setImage:[UIImage imageNamed:@"icon-Unlocked.png"] forState:UIControlStateNormal]; 
     // other statements.... 
    } 
    else 
    { 
     [btn setImage:[UIImage imageNamed:@"icon-Locked.png"] forState:UIControlStateNormal]; 
     // other statements.... 
    } 
} 
2

Swift 3 Versione (butt_img deve essere un'immagine Impostare in Assets.xcassets o immagini.cartella xcassets in Xcode):

btnTwo.setBackgroundImage(UIImage(named: "butt_img"), for: .normal) 
btnTwo.setTitle("My title", for: .normal) 

In ogni caso, se si desidera che l'immagine da scalare per riempire dimensione del pulsante, è possibile aggiungere un UIImageView su di esso e assegnare la vostra immagine:

let img = UIImageView() 
img.frame = btnTwo.frame 
img.contentMode = .scaleAspectFill 
img.clipsToBounds = true 
img.image = UIImage(named: "butt_img") 
btnTwo.addSubview(img) 
Problemi correlati