Используя iOS, как мне создать красную кнопку «удалить», аналогичную той, которая используется при удалении контактов на iPhone?
Как я могу создать большой красный UIButton в iOS?
Ответы (6)
Сначала вы начинаете с растягиваемого изображения:
Затем вы делаете кнопку с растянутым изображением в качестве фона и применяете текст.
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];
Очевидно, вам нужно будет настроить начало и размер фрейма в соответствии с вашим приложением, а также цель, селектор и заголовок.
stretchableImageWithLeftCapWidth:topCapHeight: также устарел в 5.0, в пользу resizableImageWithCapInsets:.
- person Nate; 13.06.2012
Я также сделал несколько кнопок ... версии для сетчатки и без сетчатки
Если вы хотите использовать их в ячейке, просто используйте следующий код в 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];





Я думаю, что эти лучше (и они тоже хорошо смотрятся на сетчатке):


.png, созданный из этого очень красивого файла .psd: http://www.teehanlax.com/blog/2010/08/12/iphone-4-gui-psd-retina-display/
А затем используйте его как растягиваемое изображение для фона вашего 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];
Вероятно, самый простой способ сделать это - найти этот файл Photoshop с графическим интерфейсом пользователя iPhone, содержащий множество элементов пользовательского интерфейса в слоях PSD, затем измените оттенок большой кнопки в Photoshop и сохраните ее как PNG.
Одним из преимуществ этого способа является то, что вы также можете создавать версии для выбранной кнопки и / или состояния выделения и назначать изображения стандартному UIButton.
Вы можете создать отдельный раздел в представлении сгруппированной таблицы, присвоить этому разделу только одну строку и установить для фонового изображения этой ячейки изображение с красным градиентом. Однако вам придется воссоздать это изображение самостоятельно.
Я хотел бы внести свой вклад в решение, которое не использует изображения, но которое выглядит так же, как кнопка «Удалить» в Контактах. В приведенном ниже примере я буду использовать UITableView с сгруппированными статическими ячейками, созданными в раскадровке. Сделайте так, чтобы в одной из секций была только одна ячейка. Эта ячейка будет кнопкой «удалить». Придайте ячейке красный цвет фона (например, красный 221, зеленый 0, синий 2)
Что мы сделаем, так это добавим в ячейку два GradientLayer. Первый покроет верхнюю половину клетки. Вторая закроет нижнюю половину.
Добавьте 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];
*/
}
UIGlassButtoniPhone. - person Chris S   schedule 08.03.2010