2

在 SwiftUIAlertView中已弃用并替换为UIAlertController. 正如我所见,显示 a 的唯一方法UIAlertController是通过 a UIViewController,但有时您想从 a 中显示它,让我们说UIView

现在可以使用 IOS8 和 Swift 吗?

4

2 回答 2

1

UIAlertView 在 Swift 中仍然可用,它仅在 iOS 7 中被弃用。如果您想使用最新的 iOS 8 API,我建议您执行以下操作。虽然为简单起见,如果您的目标是 iOS 7 和 iOS 8,我建议您仅使用标准 UIAlertView 而不要实现 UIAlertController。

import UIKit

class ViewController: UIViewController, UIAlertViewDelegate {

let iosVersion = NSString(string: UIDevice.currentDevice().systemVersion).doubleValue

// MARK: - IBActions

@IBAction func showAlertTapped(sender: AnyObject) {
    showAlert()
}

// MARK: - Internal

func showAlert() {

    if iosVersion >= 8 {
        var alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)

        // The order in which we add the buttons matters.
        // Add the Cancel button first to match the iOS 7 default style,
        // where the cancel button is at index 0.
        alert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
            self.handelCancel()
        }))

        alert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
            self.handelConfirm()
        }))

        presentViewController(alert, animated: true, completion: nil)
    } else {
        var alert = UIAlertView(title: "Title", message: "Message", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Confrim")

        alert.show()
    }

}

func handelConfirm() {
    println("Confirm tapped")

    // Your code
}

func handelCancel() {
    println("Cancel tapped")

    // Your code
}

// MARK: - UIAlertViewDelegate

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
    if buttonIndex == 0 {
        handelCancel()
    } else {
        handelConfirm()
    }
}

}

于 2014-10-15T09:10:07.623 回答
0
        class MyViewController: UIViewController {
@IBOutlet var myUIView: MyUIView
}

        class MyUIView: UIView {
func showAlert() {

        let parentViewController: UIViewController = UIApplication.sharedApplication().windows[1].rootViewController

        var alert = UIAlertController(title: "Title", message: "message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: {(action: UIAlertAction!) in

            println("clicked OK")
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Destructive, handler: {(action: UIAlertAction!) in

            println("clicked Cancel")

        }))
        parentViewController.presentViewController(alert, animated: true, completion: nil)

}
        - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
        {           
        }
于 2014-10-15T07:56:12.610 回答