Как настроить вид предупреждений iOS? - PullRequest
32 голосов
/ 08 апреля 2010

Я хочу создать пользовательский alert view в своем приложении для iOS. Например, я хочу добавить images в alert и изменить его цвет.

Я знаю, как создать нормальный UIAlertView, но есть ли способ настроить alert view?

Ответы [ 6 ]

39 голосов
/ 08 апреля 2010

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

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

-(void)initialDelayEnded {
    self.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.001, 0.001);
    self.view.alpha = 1.0;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:kTransitionDuration/1.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(bounce1AnimationStopped)];
    self.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);
    [UIView commitAnimations];
}

- (void)bounce1AnimationStopped {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:kTransitionDuration/2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(bounce2AnimationStopped)];
    self.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.9, 0.9);
    [UIView commitAnimations];
}

- (void)bounce2AnimationStopped {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:kTransitionDuration/2];
    self.view.transform = CGAffineTransformIdentity;
    [UIView commitAnimations];
}

У меня есть возможность короткой задержки, встроенной в класс, поэтому initialDelayEnded вызывается, когда эта задержка заканчивается.

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

12 голосов
/ 24 января 2011

Вот пользовательский вид оповещения, который я написал, который является заменой для UIAlertView. Вы можете установить пользовательское фоновое изображение; не составит труда расширить поддержку фоновых цветов.

https://github.com/TomSwift/TSAlertView

4 голосов
/ 22 октября 2011

Создайте один подкласс для UIAlertView.

И создайте общий класс для метода Alert View. Добавьте для него 2 метода ниже.

#pragma mark Alert View Functions
+(void)alertViewWithYesNo:(NSString *)pstrTitle:(NSString *)pstrMessage:(int)pstrTagId:(id)pDelegate{
UIAlertView *objAlertNotify = [[UIAlertView alloc] init];
[objAlertNotify setDelegate:pDelegate];

[objAlertNotify addButtonWithTitle:@""];
[objAlertNotify addButtonWithTitle:@""];
int intTemp = 1;
for (UIView* view in [objAlertNotify subviews])
{
    if ([[[view class] description] isEqualToString:@"UIAlertButton"])
    {
        UILabel *theTitle = [[UILabel alloc] init];
        [theTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:g_AlertFontSize]];
        [theTitle setTextColor:[UIColor whiteColor]];
        switch (intTemp) {
            case 1:
                [theTitle setText:@"Yes"];
                //[theTitle setTextColor:g_ColorYes];
                break;
            case 2:
                [theTitle setText:@"No"];
                //[theTitle setTextColor:g_ColorNo];
                break;
        }
        intTemp++;

        [theTitle setBackgroundColor:[UIColor clearColor]];             
        [theTitle setTextAlignment:UITextAlignmentCenter];
        [view addSubview:theTitle];
    }
    else if ([[[view class] description] isEqualToString:@"UIThreePartButton"])
    {
        UILabel *theTitle = [[UILabel alloc] init];
        [theTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:g_AlertFontSize]];
        [theTitle setTextColor:[UIColor whiteColor]];
        switch (intTemp) {
            case 1:
                [theTitle setText:@"Yes"];
                //[theTitle setTextColor:g_ColorYes];
                break;
            case 2:
                [theTitle setText:@"No"];
                //[theTitle setTextColor:g_ColorNo];
                break;
        }
        intTemp++;

        [theTitle setBackgroundColor:[UIColor clearColor]];             
        [theTitle setTextAlignment:UITextAlignmentCenter];
        [view addSubview:theTitle];
    }
}
[objAlertNotify setTag:pstrTagId];
[objAlertNotify setTitle:pstrTitle];
[objAlertNotify setMessage:pstrMessage];
[objAlertNotify show];
}

+(void)alertViewBtnText:(UIAlertView *)alertView{
for (UIView* view in [alertView subviews])
{
    //NSLog(@"%@", [[view class] description]);

    if ([[[view class] description] isEqualToString:@"UIAlertButton"])
    {   
        for (UILabel *lbl in [view subviews])
        {   
            //NSLog(@"%@", [[lbl class] description]);

            if ([[[lbl class] description] isEqualToString:@"UILabel"])
            {
                CGRect frame = [view bounds];

                CGSize maximumLabelSize = CGSizeMake(320,480);
                CGSize expectedLabelSize = [lbl.text sizeWithFont:lbl.font constrainedToSize:maximumLabelSize lineBreakMode:lbl.lineBreakMode];
                CGRect newFrame = lbl.frame;
                newFrame.origin.x = newFrame.origin.x - expectedLabelSize.width/2;
                newFrame.size.height = expectedLabelSize.height;
                newFrame.size.width = expectedLabelSize.width;
                lbl.frame = newFrame;
                //frame.size.width = 320.0;
                //frame.size.height = 480.0;

                lbl.frame = frame;
                [lbl setCenter:CGPointMake([view bounds].size.width/2, [view bounds].size.height/2)];
            }
        }
    }
    else if ([[[view class] description] isEqualToString:@"UIThreePartButton"])
    {   
        for (UILabel *lbl in [view subviews])
        {   
            CGRect frame = [view bounds];

            CGSize maximumLabelSize = CGSizeMake(320,480);
            CGSize expectedLabelSize = [lbl.text sizeWithFont:lbl.font constrainedToSize:maximumLabelSize lineBreakMode:lbl.lineBreakMode];
            CGRect newFrame = lbl.frame;
            newFrame.origin.x = newFrame.origin.x - expectedLabelSize.width/2;
            newFrame.size.height = expectedLabelSize.height;
            newFrame.size.width = expectedLabelSize.width;
            lbl.frame = newFrame;
            //frame.size.width = 320.0;
            //frame.size.height = 480.0;

            lbl.frame = frame;
            [lbl setCenter:CGPointMake([view bounds].size.width/2, [view bounds].size.height/2)];
        }
    }
}
}

Теперь, в любом классе, вы используете это пользовательское оповещение: Добавить ниже:

#pragma mark UIAlertViewDelegate
-(void)willPresentAlertView:(UIAlertView *)alertView{

if(alertView==objAlertMsg){
    /*clsCommonFuncDBAdapter *objclsCommonFuncDBAdapter = [[clsCommonFuncDBAdapter alloc] init];
    float newHeight = [objclsCommonFuncDBAdapter getAlertHeightByMessage:alertView.frame.size.width :alertView.message] + [g_AlertExtraHeight intValue];
    [objclsCommonFuncDBAdapter release];

    //NSLog(@"X = %f, Y = %f, Widht = %f, Height = %f", alertView.frame.origin.x, alertView.frame.origin.y, alertView.frame.size.width, alertView.frame.size.height);
    //[alertView setFrame:CGRectMake(alertView.frame.origin.x, alertView.frame.origin.y, alertView.frame.size.width, 110.0)];
    [alertView setFrame:CGRectMake(alertView.frame.origin.x, alertView.frame.origin.y, alertView.frame.size.width, newHeight)];*/
}

[clsCommonFuncDBAdapter alertViewBtnText:alertView];

}

Для вызова: Используйте как показано ниже:

-(void)askForGPSEnable{
[clsCommonFuncDBAdapter alertViewWithYesNo:msgGPSTitle :msgGPSMessage :0 :self];
}

Дайте мне знать, если возникнут какие-либо трудности.

2 голосов
/ 26 ноября 2010

http://iphonedevelopment.blogspot.com/2010/05/custom-alert-views.html

и

http://www.skylarcantu.com/blog/2009/08/14/custom-uialertview-color-chooser/

Вы можете использовать вышеуказанные ссылки для пользовательских оповещений. Надеюсь, они вам пригодятся.

2 голосов
/ 08 апреля 2010

Вам потребуется создать собственный настраиваемый вид и реализовать некоторое поведение стиля представления предупреждений, например, отображение модально, затемнение фона, анимацию входа и выхода и т. Д.

В SDK нет поддержки для настройки UIAlertView дальше, чем текст или кнопки.

1 голос
/ 08 апреля 2016

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

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