减少警报视图编码

时间:2015-06-26 07:17:29

标签: ios objective-c iphone cocoa-touch xcode6

全部。 在我的iOS应用程序中。 在许多网页上,我有 Too many alerts and also with many Network conditions.

有太多警报文本,我厌倦了。 每次我必须使用相同的代码。

我可以在某个助手类中声明此代码吗? 或者重复使用此代码?

-(BOOL)checkInternetAndlocationServices {

    if(IS_INTERNET) {
        if([CLLocationManager locationServicesEnabled] &&
           [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied){
            return YES;
        }
        else
        {
            NSLog(@"Location services are disabled.");
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Location services are off." message:@"This app requires an Location services." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Location Services", nil];
            [alert setTag:NO_LOCATIONSERVICES];
            [alert show];
            return NO;
        }
    }
    else
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Internet connection is off." message:@"This app requires an internet connection and locations services, please enable internet connection and location services." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Settings", nil];
        [alert setTag:NO_INTERNET];
        [alert show];
        return NO;
    }
}

感谢。 如果您觉得有用,请编辑此问题。

感谢您提供良好的方法,还有其他任何方式,最受欢迎的例子。

2 个答案:

答案 0 :(得分:5)

  1. 您可以创建一个帮助类并使用类方法来显示警报。
  2. 您还可以制作UIAlertView类别并制作用于显示提醒的类方法。(编辑)
     
    @implementation UIAlertView (MyAlert)
    +(void) showAlertWithTitle:(NSString *)title message:(NSString *)message {
    [[[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    }
    @end
    
  3. 您可以在.pch文件或某个帮助程序头文件中定义宏以显示警告。
    #define Alert(title,msg,target) [[[UIAlertView alloc] initWithTitle:title message:msg delegate:target cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show]
    Alert(@"This is Title",@"This is message",self);

答案 1 :(得分:2)

你可以创建一个NSObject类并编写像这样的Instance或Class方法的方法,只传递消息和委托是否需要设置nil或self这样: -

 +(void)showAlertViewWithAlertMessage:(NSString*)alertMessage withDelegate:(id)delegate
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Title" message:alertMessage delegate:delegate cancelButtonTitle:OK_TAP otherButtonTitles: nil];
        [alert show];
    }

您可以像这样使用它: -         [Classname showAlertViewWithAlertMessage:@“你的消息”withDelegate:nil];