Я хотел бы предложить решение, которое не использует изображения, но которое выглядит так же, как кнопка «Удалить» в Контактах.
В приведенном ниже примере я буду использовать UITableView с сгруппированными , статическими ячейками, созданными в раскадровке. Сделать из одного из разделов только одну ячейку. Эта ячейка будет кнопкой «Удалить». Придайте ячейке красный фоновый цвет (например, красный 221, зеленый 0, синий 2)
Что мы сделаем, это добавим два слоя GradientLayers в ячейку. Первый покроет верхнюю половину ячейки. Второй покроет нижнюю половину.
Добавьте QuartzCore в ваш файл реализации:
#import <QuartzCore/QuartzCore.h>
Начните с создания выхода в эту ячейку:
@property (strong, nonatomic) IBOutlet UITableViewCell *cellDelete;
Создайте метод, в котором ячейка будет отформатирована:
- (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];
}
Вышеуказанное придаст вашей ячейке внешний вид, аналогичный кнопке «Удалить» в Контактах.
Но мы также хотим, чтобы он менял цвет, когда пользователь нажимает на него. Это то, что будет делать последний фрагмент кода в приведенном выше методе. Будет установлен другой вид с более темным цветом, как selectedBackgroundView.
После нажатия ячейка останется выделенной и сохранит свой темный цвет. Чтобы автоматически отменить выбор ячейки, мы делаем следующее:
Начните с константы, которая определяет номер раздела вашей ячейки удаления:
static NSInteger const SECTION_DELETE = 1;
Теперь реализуйте метод (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
(определенный в 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];
*/
}