Como posso criar um grande, vermelho UIButton com iOS?
-
07-07-2019 - |
Pergunta
Usando o iOS, como eu iria sobre como criar um botão vermelho semelhante ao utilizado "delete" ao excluir contatos no iPhone?
Solução
Você começa com uma imagem elástica:
Em seguida, você fazer um botão com a imagem esticada como pano de fundo e aplicar texto.
UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(kLeftMargin, 10, self.view.bounds.size.width - kLeftMargin - kRightMargin, 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];
Obviamente, você precisará ajustar a origem eo tamanho do quadro para coincidir com a sua aplicação, bem como o alvo, seletor, e título.
Outras dicas
Eu também fiz algumas versões botões ... retina e não-retina
Se você quiser usá-los em um celular basta usar o seguinte código no cellForRowAtIndexPath:
UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:[cell.contentView frame]];
[sampleButton setFrame:CGRectMake(0, 0, cell.bounds.size.width-20, 44)];
[sampleButton setBackgroundImage:[UIImage imageNamed:@"button_red.png"] forState:UIControlStateNormal];
[cell addSubview:sampleButton];
Eu acho que aqueles são melhores (e eles parecem bem em exibição retina também):
.png gerado a partir deste arquivo .psd muito agradável: http://www.teehanlax.com/blog/2010/08/12/iphone-4-gui-psd-retina-display/
E, em seguida, usá-lo como uma imagem strechable para o fundo do seu UIButton
:
UIImage* greenButton = [UIImage imageNamed:@"UIButton_green.png"];
UIImage *newImage = [greenButton stretchableImageWithLeftCapWidth:greenButton.size.width/2 topCapHeight:greenButton.size.height/2];
[callButton setBackgroundImage:newImage forState:UIControlStateNormal];
Provavelmente, a maneira mais simples de fazê-lo é senão esse arquivo iPhone GUI Photoshop que contém muitos elementos de interface do usuário em camadas PSD, em seguida, mudar o tom da grande botão no Photoshop e salvá-lo como um PNG.
Uma das vantagens de fazê-lo desta maneira é que você também pode criar versões para botão selecionado e / ou estado de destaque e atribuir as imagens para um UIButton padrão.
Você pode criar uma seção separada em sua exibição de tabela agrupada, dar essa seção apenas uma linha, e conjunto que imagem de fundo da célula para a imagem de um gradiente vermelho. Você vai ter que recriar a imagem em seu próprio país, no entanto.
Gostaria de contribuir com uma solução que não usa imagens, mas que dá a mesma aparência que o botão 'delete' em Contatos. No exemplo abaixo eu vou usar assumir um UITableView com Agrupados , as células estáticas, projetados em storyboard. Faça uma das seções têm apenas uma única célula. Essa célula será o botão 'delete'. Dê a célula uma cor de fundo vermelha (F. E. Vermelho 221, verde 0, Azul 2)
O que vamos fazer é adicionar duas GradientLayers para a célula. A primeira vai cobrir a parte superior da célula. O segundo cobrirá a metade inferior.
Adicionar QuartzCore ao seu arquivo de implementação:
#import <QuartzCore/QuartzCore.h>
Comece com fazer uma saída para esta célula:
@property (strong, nonatomic) IBOutlet UITableViewCell *cellDelete;
Criar um método no qual a célula será formatada:
- (void)formatCellDelete
{
// Top Gradient //
CAGradientLayer *gradientTop = [CAGradientLayer layer];
// Make a frame for the layer based on the size of the cells contentView
// Make it half the height
// The width will be -20 so the gradient will not overflow
CGRect frame = CGRectMake(0, 0, _cellDelete.contentView.frame.size.width - 20, _cellDelete.contentView.frame.size.height / 2);
gradientTop.frame = frame;
gradientTop.cornerRadius = 8;
UIColor* topColor = [UIColor colorWithWhite:1.0f alpha:0.75f];
UIColor* bottomColor = [UIColor colorWithWhite:1.0f alpha:0.0f];
gradientTop.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];
[_cellDelete.contentView.layer setMasksToBounds:YES];
[_cellDelete.contentView.layer insertSublayer:gradientTop atIndex:0];
// Bottom Gradient //
CAGradientLayer *gradientBottom = [CAGradientLayer layer];
// Make a frame for the layer based on the size of the cells contentView
// Make it half the height
// The width will be -20 so the gradient will not overflow
frame = CGRectMake(0, 0, _cellDelete.contentView.frame.size.width - 20, _cellDelete.contentView.frame.size.height / 2);
// And move to bottom
frame.origin.y = frame.size.height;
gradientBottom.frame = frame;
topColor = [UIColor colorWithWhite:0.0f alpha:0.05f]; //0.20
bottomColor = [UIColor colorWithWhite:0.0f alpha:0.0f];
gradientBottom.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];
[_cellDelete.contentView.layer setMasksToBounds:YES];
[_cellDelete.contentView.layer insertSublayer:gradientBottom atIndex:0];
// Define a selected-backgroundColor so the cell changes color when the user tabs it
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor colorWithRed:(float)(0.502) green:0.0 blue:0.0 alpha:1.000]];
bgColorView.layer.cornerRadius = 10;
[_cellDelete setSelectedBackgroundView:bgColorView];
}
O acima irá dar o seu celular o vidro-olhar como o botão 'delete' em Contatos. Mas também queremos que ele mude de cor quando o usuário toca-lo. Isto é o que o último pedaço de código no método acima irá fazer. Ele irá definir uma visão diferente, com uma cor mais escura como o selectedBackgroundView.
Depois de tocar a célula permanecerá selecionado e irá manter sua cor escura. Para desmarcar automaticamente a célula que faça o seguinte:
Comece com uma constante que define o nr seção de seu celular de exclusão:
static NSInteger const SECTION_DELETE = 1;
Agora implementar o método (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
(definido no UITableViewDelegate):
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == SECTION_DELETE){
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
// Navigation logic may go here. Create and push another view controller.
/*
 *detailViewController = [[ alloc] initWithNibName:@"" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}