Как я могу создать большой красный UIButton с iOS? - PullRequest
52 голосов
/ 15 сентября 2009

Как использовать iOS для создания красной кнопки «Удалить», аналогичной той, которая использовалась при удалении контактов на iPhone?

Ответы [ 6 ]

85 голосов
/ 15 сентября 2009

Вы начинаете с растягиваемого изображения:

альтернативный текст http://grab.by/4lP

Затем вы делаете кнопку с растянутым изображением в качестве фона и применяете текст.

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

Очевидно, вам нужно будет настроить происхождение и размер фрейма в соответствии с вашим приложением, а также с целью, селектором и заголовком.

62 голосов
/ 24 ноября 2010

Я также сделал несколько кнопок ... версии для сетчатки и без сетчатки

Если вы хотите использовать их в ячейке, просто используйте следующий код в 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];

Green Button Normal

Red Button Normal

Grey Button Normal

Green Button Retina Red Button Retina Grey Button Retina

22 голосов
/ 09 сентября 2010

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

alt text alt text

.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];

2 голосов
/ 15 сентября 2009

Вероятно, самый простой способ сделать это - поймать этот файл Photoshop с графическим интерфейсом iPhone , который содержит множество элементов пользовательского интерфейса в слоях PSD, затем изменить оттенок большой кнопки в Photoshop и сохранить его в формате PNG .

Одним из преимуществ такого способа является то, что вы также можете создавать версии для выбранной кнопки и / или выделять состояние и назначать изображения стандартной UIButton.

0 голосов
/ 28 марта 2013

Я хотел бы предложить решение, которое не использует изображения, но которое выглядит так же, как кнопка «Удалить» в Контактах. В приведенном ниже примере я буду использовать 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];
     */

}
0 голосов
/ 15 сентября 2009

Вы можете создать отдельный раздел в вашем сгруппированном табличном представлении, дать этому разделу только одну строку и установить для фонового изображения этой ячейки изображение с красным градиентом. Однако вам придется воссоздать это изображение самостоятельно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...