Как добавить кнопку «Отмена» между двумя другими кнопками (в стеке) в UIAlertView (iOS) - PullRequest
2 голосов
/ 03 апреля 2012

Я пытаюсь создать UIAlertView с тремя кнопками (которые будут сложены).Я бы хотел, чтобы кнопка «Отмена» находилась посередине между двумя другими кнопками.Я попытался установить для cancelButtonIndex значение 1, но если есть две другие кнопки, он просто помещает их в индексы 0 и 1. Я знаю, что могу просто изменить названия кнопок, но я хочу более темно-синее форматирование кнопки отмены.

РЕДАКТИРОВАТЬ: ** Пожалуйста, обратите внимание - я знаю, как получить три кнопки с заголовками в правильном порядке, но только если все три кнопки по сути похожи на «другие» кнопки;Я хочу, чтобы кнопка отмены имела кнопку отмены темно-синий фон , чтобы она выглядела как обычная кнопка отмены.**

Я пробовал

UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:button1Title,button2Title,nil] autorelease];
alert.cancelButtonIndex = 1;
[alert show];

и

UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil] autorelease];
alert.cancelButtonIndex = 1;
[alert addButtonWithTitle:button1Title];
[alert addButtonWithTitle:button2Title];
[alert show];

и

UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:addButtonWithTitle:button1Title,nil] autorelease];
alert.cancelButtonIndex = 1;
[alert addButtonWithTitle:button2Title];
[alert show];

безрезультатно.Можно ли даже выполнить то, что я пытаюсь сделать?

Ответы [ 4 ]

3 голосов
/ 03 апреля 2012
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title message:msg delegate:self        cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
[alert addButtonWithTitle:button1Title];
[alert addButtonWithTitle:@"Cancel"];
[alert addButtonWithTitle:button2Title];
[alert show];

Might Help,

Приветствие.

2 голосов
/ 04 апреля 2012

У меня есть два дополнительных замечания к этому ответу.

1) Хотя, насколько мне известно, Apple не отклонила приложение для разумного изменения UIAlertView;Они сказали, что иерархия представлений классов, таких как UIAlertView, должна рассматриваться как частная.

2) Этот вопрос является хорошим примером того, почему вы должны задать вопрос больше о своей конечной цели, а не о шагах, которые нужно получить.там.Единственная причина, по которой я знаю, о чем этот вопрос, - это комментарий, оставленный в моем ответе здесь .

Ответ:

Потому чтоиз вашего комментария я знаю, что вы хотите создать UIAlertView, в котором кнопки расположены в стеке, даже когда есть только две кнопки.

Я считаю, что наиболее логичное место для кода, как это, находится в категории.Поскольку обычно код, необходимый для управления просмотром предупреждений, должен быть вокруг вызова show, я создал метод категории, который я вызываю, вместо show, а метод, в свою очередь, вызывает show.

-(void)showWithButtonsStacked{
    static NSString *tempButtonTitle = @"SomeUnlikelyToBeUsedTitle";
    BOOL willAddFakeButton = (self.numberOfButtons == 2); // Button are only side by side when there's 2
    if (willAddFakeButton){
        self.clipsToBounds = YES;
        [self addButtonWithTitle:tempButtonTitle]; // add temp button so the alertview will stack
    }
    BOOL hasCancelButton = (self.cancelButtonIndex != -1); // If there is a cancel button we don't want to cut it off
    [self show];
    if (willAddFakeButton){
        UIButton *cancelButton = nil;
        UIButton *tempButton = nil;
        for (UIButton *button in self.subviews) {
            if ([button isKindOfClass:[UIButton class]]){
                if (hasCancelButton && [button.titleLabel.text isEqualToString:[self buttonTitleAtIndex:self.cancelButtonIndex]]){
                    cancelButton = button;
                } else if ([button.titleLabel.text isEqualToString:tempButtonTitle]) {
                    tempButton = button;
                }
            }
        }
        if (hasCancelButton){ // move in cancel button
            cancelButton.frame = tempButton.frame;
        }
        [tempButton removeFromSuperview];

        // Find lowest button still visable.
        CGRect lowestButtonFrame = CGRectZero;
        for (UIButton *button in self.subviews) {
            if ([button isKindOfClass:[UIButton class]]){
                if (button.frame.origin.y > lowestButtonFrame.origin.y){
                    lowestButtonFrame = button.frame;
                }
            }
        }

        // determine new height of the alert view based on the lowest button frame
        CGFloat newHeight = CGRectGetMaxY(lowestButtonFrame) + (lowestButtonFrame.origin.x * 1.5);
        self.bounds = CGRectMake(0, 0, self.bounds.size.width, newHeight);        
    }
}

Способ, которым этот метод выполняет свою цель, состоит в том, чтобы добавить временную кнопку в представление предупреждений, чтобы заставить представление предупреждений складывать кнопки, затем он удаляет временную кнопку и регулирует высоту.Поскольку это метод категории, вы можете использовать его, просто позвонив по номеру:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Test title" message:@"message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alert showWithButtonsStacked];

Этот код приводит к появлению следующего предупреждения:

enter image description here

2 голосов
/ 03 апреля 2012
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
[alert addButtonWithTitle:button1Title];
[alert addButtonWithTitle:@"Cancel"];
[alert addButtonWithTitle:button2Title];
[alert setCancelButtonIndex:1]; // to make it look like cancel button
[alert show];
0 голосов
/ 03 апреля 2012

Установите кнопку отмены на nil и просто добавьте ее вместо остальных кнопок

...