减少警报视图编码

Reduce alert view coding

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

警报文本太多,我受够了。 每次我都必须输入相同的代码。

我可以在 Some Helper Class 中声明此代码吗? 或者重复使用此代码?

-(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;
    }
}

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

感谢提供好的方法,还有其他方法,欢迎举例。

  1. 您可以制作一个助手 class 并使用 class 方法来显示警报。
  2. 您还可以制作一个 UIAlertView 类别并制作一个 class 方法来显示警报。(编辑)
     
    @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);

你可以创建一个 NSObject class 并编写方法,无论是 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];
    }

你可以这样使用它:- [Class名称 showAlertViewWithAlertMessage:@"your message" withDelegate:nil];