Por que não apresentar título UIButton?
-
20-08-2019 - |
Pergunta
No método viewDidLoad do UIViewController, eu faço isso:
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);
O botão exibe, mas o título não faz. A linha de NSLog impressões "Testing" para o console. Todas as sugestões sobre o que estou fazendo de errado?
Solução
Eu não posso te dizer por que ele não funciona, mas eu tenho uma solução:
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];
Separe a criação do quadro de alocação e inicialização do botão.
Outras dicas
As mentiras de problema com
UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect]
initWithFrame:CGRectMake(0, 0, 100, 100)];
buttonWithType
retorna um objeto inicializado autoreleased. Você não pode enviar-lhe uma initWithFrame novamente como um objeto só pode ser inicializado uma vez.
Defina seu quadro separadamente:
b.frame = CGRectMake(0, 0, 100, 100);
Faça isso em vez disso:
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];
A coisa é que você tem que ir para [[UIButton alloc] initWithFrame:]
ou [UIButton buttonWithType:]
, você não deve usar os dois juntos.
Você pode fazer o seguinte:
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];
Eu tive o mesmo problema e ele acabou sendo o fato de que eu estava arrumando a imagem em vez do backgroundImage. Tudo funcionou bem quando eu fiz:
[button setBackgroundImage:image forState:UIControlStateNormal];