2

SwiftUIAlertViewでは廃止され、 に置き換えられましたUIAlertController。私が見たように、 a を表示する唯一の方法UIAlertControllerは a を使用することですが、場合によっては aUIViewControllerから表示したい場合があります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 に答える