UIAlertController if iOS 8, otherwise UIAlertView

2020-02-10 01:07发布

I want to conform to the UIAlertController used in iOS 8 since UIAlertView is now deprecated. Is there a way that I can use this without breaking support for iOS 7? Is there some kind of if condition I can do to check for iOS 8 otherwise do something else for iOS 7 support?

11条回答
唯我独甜
2楼-- · 2020-02-10 01:46

I have created very simple wrapper in Objective-C, that supports both - old iOS UIAlertView and new one UIAlertViewController

https://github.com/MartinPerry/UIAlert/

It also brings the new action blocks usage to old UIAlertView

Sample:

MyAlertMessage * a = [[MyAlertMessage alloc] initWithTitle:@"Hello" WithMessage:@"World"];

[a addButton:BUTTON_OK WithTitle:@"OK" WithAction:^(void *action) { 
  NSLog(@"Button OK at index 0 click"); 
}];

[a addButton:BUTTON_CANCEL WithTitle:@"Cancel" WithAction:^(void *action) {
  NSLog(@"Button Cancel at index 1 click"); 
}];

[a show];
查看更多
Root(大扎)
3楼-- · 2020-02-10 01:46

Method one

by ios system version check

#define iOSVersionLessThan(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
// below ios8 ,create UIAlertView
if(iOSVersionLessThan(@"7.0")){
     // todo

// ios8 and above ,UIActionController avaliable
}else{
    // todo
}

Method two

by system feature detect

// create UIActionController 
if([UIActionController class]){
    // todo
// create UIAlertView
}else{
    // todo
}

But,there's a third lib named PSTAlertController that deal with backwards compatible to iOS 7 of UIActionSheet and UIAlertView.

ref to

查看更多
Viruses.
4楼-- · 2020-02-10 01:50

As others have already mentioned - always check whether a feature exists. I believe the safest approach is following:

if (NSClassFromString(@"UIAlertController")) {
    // use UIAlertController
} else {
    // use UIAlertView
}

With the obvious risk of entering a class name with a typo. :)

From documentation of NClassFromString:

[Returns] The class object named by aClassName, or nil if no class by that name is currently loaded. If aClassName is nil, returns nil.

Availability iOS (2.0 and later)

查看更多
甜甜的少女心
5楼-- · 2020-02-10 01:51
// Above ios 8.0
float os_version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (os_version >= 8.000000)
{
      //Use UIAlertController    
}
else
{
     //UIAlertView
}
查看更多
何必那么认真
6楼-- · 2020-02-10 01:52

Please see the answer of Erwan (below my answer) as I see it is the best.

--

You can check the iOS version to use appropriate control like this:

if (([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] == NSOrderedAscending)) {
    // use UIAlertView
}
else {
    // use UIAlertController
}
查看更多
登录 后发表回答