可在iOS 7和iOS 8上运行的警报

Ant*_*hko 11 backwards-compatibility ios swift

我正在得到dyld:未找到符号:_OBJC_CLASS _ $ _ UIAlertAction当我试图让这个怪物运行时.

我如何弱连接8.0的东西?

var device : UIDevice = UIDevice.currentDevice()!;
var systemVersion = device.systemVersion;
var iosVerion : Float = systemVersion.bridgeToObjectiveC().floatValue;
if(iosVerion < 8.0) {
    let alert = UIAlertView()
    alert.title = "Noop"
    alert.message = "Nothing to verify"
    alert.addButtonWithTitle("Click")
    alert.show()
} else {
    var alert : UIAlertController? = UIAlertController(title: "Noop", message: "Nothing to verify", preferredStyle: UIAlertControllerStyle.Alert)
    if alert {
        let actionStyle : UIAlertActionStyle? = UIAlertActionStyle.Default;
        var alertAction : UIAlertAction? = UIAlertAction(title: "Click", style: actionStyle!, handler: nil)
        if(alertAction) {
            alert!.addAction(alertAction)
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}
return;
Run Code Online (Sandbox Code Playgroud)

已解决:UIKit必须标记为Optional而不是Required.简化版现在是:

var device : UIDevice = UIDevice.currentDevice()!;
var systemVersion = device.systemVersion;
var iosVerion : Float = systemVersion.bridgeToObjectiveC().floatValue;
if(iosVerion < 8.0) {
    let alert = UIAlertView()
    alert.title = "Noop"
    alert.message = "Nothing to verify"
    alert.addButtonWithTitle("Click")
    alert.show()
} else {
    var alert : UIAlertController = UIAlertController(title: "Noop", message: "Nothing to verify", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Click", style:.Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

s4y*_*s4y 5

  • 在项目构建阶段的"Link Binary With Libraries"部分中明确添加UIKit.

  • 您可以像这样测试UIAlertController的存在:

    if NSClassFromString("UIAlertController") != nil {
        // Use it
    } else {
        // Fall back
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 我写了一个适用于iOS 7和iOS 8的包装器.你可以在这里找到它.它需要一个视图控制器,后跟一堆可选参数和任意数量的按钮:

    showAlert(self, style: .ActionSheet, sourceView: cell, completion: {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    },
        (.Default, "Send clipboard", {
            if someCondition {
                // completion must be specified because of a Swift bug (rdar://18041904)
                showAlert(self, title: "Nothing to send", message: "The clipboard is empty.", completion: nil,
                    (.Cancel, "OK", nil)
                )
            }
        }),
        (.Cancel, "Cancel", nil)
    )
    
    Run Code Online (Sandbox Code Playgroud)