Eu preciso de um UIButtoncom imagem e texto . A imagem deve estar na parte superior e o texto está embaixo da imagem, ambos devem ser clicáveis.
Eu preciso de um UIButtoncom imagem e texto . A imagem deve estar na parte superior e o texto está embaixo da imagem, ambos devem ser clicáveis.
Respostas:
Eu vejo respostas muito complicadas, todas usando código. No entanto, se você estiver usando o Interface Builder , existe uma maneira muito fácil de fazer isso:


Você pode até usar a mesma abordagem por código, sem criar UILabels e UIImages dentro das outras soluções propostas. Mantenha-o sempre simples!
EDIT: anexado um pequeno exemplo com as 3 coisas definidas (título, imagem e plano de fundo) com inserções corretas

Backgroundimagem em vez de Image, caso contrário você não verá o título nem definirá os valores inseridos para reposicionar o título.
Acho que você está procurando esta solução para o seu problema:
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setFrame:CGRectMake(0.f, 0.f, 128.f, 128.f)]; // SET the values for your wishes
[_button setCenter:CGPointMake(128.f, 128.f)]; // SET the values for your wishes
[_button setClipsToBounds:false];
[_button setBackgroundImage:[UIImage imageNamed:@"jquery-mobile-icon.png"] forState:UIControlStateNormal]; // SET the image name for your wishes
[_button setTitle:@"Button" forState:UIControlStateNormal];
[_button.titleLabel setFont:[UIFont systemFontOfSize:24.f]];
[_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; // SET the colour for your wishes
[_button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; // SET the colour for your wishes
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, -110.f, 0.f)]; // SET the values for your wishes
[_button addTarget:self action:@selector(buttonTouchedUpInside:) forControlEvents:UIControlEventTouchUpInside]; // you can ADD the action to the button as well like
... o restante da personalização do botão é seu dever agora e não se esqueça de adicionar o botão à sua visualização.
ATUALIZAÇÃO # 1 e ATUALIZAÇÃO # 2
ou, se você não precisar de um botão dinâmico, poderá adicioná-lo à sua exibição no Interface Builder e também poderá definir os mesmos valores. é bem parecido, mas aqui está essa versão também em uma imagem simples.
você também pode ver o resultado final no Interface Builder, como está na captura de tela.

O Xcode-9 e o Xcode-10 da Apple fizeram algumas alterações em relação ao Edge Inset agora, você pode alterá-lo no inspetor de tamanho.
Siga os passos abaixo:
Etapa 1: insira o texto e selecione a imagem que deseja mostrar:
Etapa 2: selecione o controle de botão conforme sua exigência, como mostrado na imagem abaixo:
Etapa 3: Agora insira o tamanho do inspetor e agregue valor conforme sua exigência:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.imageView.image = [UIImage imageNamed:@"your image name here"];
button.titleLabel.text = @"your text here";
mas o código a seguir mostrará o rótulo acima e a imagem em segundo plano
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.background.image = [UIImage imageNamed:@"your image name here"];
button.titleLabel.text = @"your text here";
Não há necessidade de usar o rótulo e o botão no mesmo controle porque o UIButton possui as propriedades UILabel e UIimageview.
Use este código:
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.imageView.frame=CGRectMake(0.0f, 0.0f, 50.0f, 44.0f);///You can replace it with your own dimensions.
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 35.0f, 50.0f, 44.0f)];///You can replace it with your own dimensions.
[button addSubview:label];
Use este código:
UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(0, 10, 200, 52)];
[sampleButton setTitle:@"Button Title" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];
[sampleButton setBackgroundImage:[[UIImage imageNamed:@"redButton.png"]
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[sampleButton addTarget:self action:@selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton]
Encontrei o mesmo problema e o corrigi criando uma nova subclasse UIButtone substituindo o layoutSubviews:método como abaixo:
-(void)layoutSubviews {
[super layoutSubviews];
// Center image
CGPoint center = self.imageView.center;
center.x = self.frame.size.width/2;
center.y = self.imageView.frame.size.height/2;
self.imageView.center = center;
//Center text
CGRect newFrame = [self titleLabel].frame;
newFrame.origin.x = 0;
newFrame.origin.y = self.imageView.frame.size.height + 5;
newFrame.size.width = self.frame.size.width;
self.titleLabel.frame = newFrame;
self.titleLabel.textAlignment = UITextAlignmentCenter;
}
Penso que a resposta de Angel García Olloqui é outra boa solução, se você as colocar manualmente no construtor de interfaces, mas manterei minha solução, pois não preciso modificar as inserções de conteúdo de cada botão.
Faça UIImageViewe UILabele imagem Jogo e texto para ambos isso .... Em seguida, coloque um botão personalizado sobre imageView e Etiqueta ....
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search.png"]];
imageView.frame = CGRectMake(x, y, imageView.frame.size.width, imageView.frame.size.height);
[self.view addSubview:imageView];
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y,a,b)];
yourLabel.text = @"raj";
[self.view addSubview:yourLabel];
UIButton * yourBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[yourBtn setFrame:CGRectMake(x, y,c,d)];
[yourBtn addTarget:self action:@selector(@"Your Action") forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourBtn];
Você deve criar uma visualização de imagem personalizada para imagem e um rótulo personalizado para texto e adicionar ao seu botão como sub-visualizações. É isso aí.
UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
yourButton.backgroundColor = [UIColor greenColor];
yourButton.frame = CGRectMake(140, 40, 175, 30);
[yourButton addTarget:self action:@selector(yourButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourButton];
UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, yourButton.frame.size.width, yourButton.frame.size.height/2)];
imageView1.image =[UIImage imageNamed:@"images.jpg"];
[yourButton addSubview:imageView1];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height/2)];
label.backgroundColor = [UIColor greenColor];
label.textAlignment= UITextAlignmentCenter;
label.text = @"ButtonTitle";
[yourButton addSubview:label];
Para fins de teste, use o yourButtonSelected:método
-(void)yourButtonSelected:(id)sender{
NSLog(@"Your Button Selected");
}
Eu acho que será útil para você.
É realmente simples, basta adicionar uma imagem ao plano de fundo do seu botão e fornecer um texto para o título do botão para obter um controle normal. É isso aí.
[btn setBackgroundImage:[UIImage imageNamed:@"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:@"Click Me" forState:UIControlStateNormal];