Domanda

Nel metodo viewDidLoad di un UIViewController, faccio questo:

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
                                       initWithFrame:CGRectMake(0, 0, 100, 100)];

[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];                       // EDIT: should be 'b'
NSLog(@"button title: %@", [b titleLabel].text);

Il pulsante viene visualizzato ma il titolo no. La riga NSLog stampa & Quot; Test & Quot; alla console. Qualche suggerimento su cosa sto facendo di sbagliato?

È stato utile?

Soluzione

Non posso dirti perché non funziona, ma ho una soluzione:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;        
b. frame = CGRectMake(0, 0, 100, 100);

[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self addSubview:b];   

Creazione separata del frame dall'allocazione e dall'init del pulsante.

Altri suggerimenti

Il problema sta con

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
                                       initWithFrame:CGRectMake(0, 0, 100, 100)];

buttonWithType restituisce un oggetto inizializzato rilasciato automaticamente. Non è possibile inviare nuovamente un initWithFrame poiché un oggetto può essere inizializzato solo una volta.

Imposta la sua cornice separatamente:

b.frame = CGRectMake(0, 0, 100, 100);

Procedi invece:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(0, 0, 100, 100);
[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];  

Il fatto è che devi scegliere [[UIButton alloc] initWithFrame:] o [UIButton buttonWithType:], non dovresti usarli entrambi insieme.

Puoi fare quanto segue:

UIButton *b=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];

b=[UIButton buttonWithType:UIButtonTypeRoundedRect];

[b setTitle:@"Button Title Here" forState:UIControlStateNormal];
[b setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];

Ho avuto lo stesso problema e alla fine è stato il fatto che stavo impostando l'immagine anziché l'immagine di sfondo. Tutto ha funzionato bene quando l'ho fatto:

[button setBackgroundImage:image forState:UIControlStateNormal];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top