Pregunta

Usando iOS, ¿cómo haría para crear una " eliminar " roja botón similar al que se usa al eliminar contactos en el iPhone?

¿Fue útil?

Solución

Primero comienza con una imagen extensible:

texto alternativo http://grab.by/4lP

Luego haces un botón con la imagen estirada como fondo y aplicas el 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, deberá ajustar el origen y el tamaño del marco para que coincida con su aplicación, así como con el objetivo, el selector y el título.

Otros consejos

También hice algunos botones ... versiones retina y no retina

Si desea usarlos en una celda, simplemente use el siguiente código en 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];

Botón verde Normal

Botón rojo Normal

Botón gris Normal

Retina del botón verde Retina del botón rojo Retina de botón gris

Creo que esos son mejores (y también se ven bien en la pantalla de retina ):

texto alternativo texto alternativo ??

.png generado a partir de este muy buen archivo .psd: http://www.teehanlax.com/blog/2010/08/12/iphone-4-gui-psd-retina-display/

Y luego úselo como una imagen extensible para el fondo de su 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];

Probablemente la forma más sencilla de hacerlo es enganchar este archivo de Photoshop GUI de iPhone que contiene muchos elementos de la interfaz de usuario en capas PSD, luego cambie el tono del botón grande en Photoshop y guárdelo como PNG.

Una ventaja de hacerlo de esta manera es que también puede crear versiones para el botón seleccionado y / o resaltar el estado y asignar las imágenes a un UIButton estándar.

Puede crear una sección separada en su vista de tabla agrupada, asignar a esa sección solo una fila y establecer la imagen de fondo de esa celda en una imagen de degradado rojo. Sin embargo, tendrá que recrear esa imagen por su cuenta.

Me gustaría aportar una solución que no use imágenes pero que tenga el mismo aspecto que el botón 'eliminar' en Contactos. En el siguiente ejemplo, usaré asumir un UITableView con agrupadas , celdas estáticas, diseñadas en storyboard. Haga que una de las secciones tenga una sola celda. Esa celda será el botón 'eliminar'. Dé a la celda un color de fondo rojo (p. Ej., Rojo 221, verde 0, azul 2)

Lo que haremos es agregar dos GradientLayers a la celda. El primero cubrirá la mitad superior de la celda. El segundo cubrirá la mitad inferior.

Agregue QuartzCore a su archivo de implementación:

#import <QuartzCore/QuartzCore.h>

Comience por hacer una salida a esta celda:

@property (strong, nonatomic) IBOutlet UITableViewCell *cellDelete;

Cree un método en el que se formateará la celda:

- (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];
}

Lo anterior le dará a su celular el aspecto de vidrio como el botón 'eliminar' en Contactos. Pero también queremos que cambie de color cuando el usuario lo toque. Esto es lo que hará el último fragmento de código del método anterior. Establecerá una vista diferente con un color más oscuro como la vista de fondo seleccionada.

Después de tocar, la celda permanecerá seleccionada y mantendrá su color oscuro. Para deseleccionar automáticamente la celda, hacemos lo siguiente:

Comience con una constante que defina la sección nr de su celda de eliminación:

static NSInteger const SECTION_DELETE = 1;

Ahora implemente el (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath (definido en 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];
     */

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top