在Swift中UIAlertView
已弃用,已替换为UIAlertController
。我看到显示UIAlertController
的唯一方法是通过UIViewController
,但有时您想通过简单的UIView
显示它。
现在可以使用IOS8和Swift吗?
答案 0 :(得分: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()
}
}
}
答案 1 :(得分: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
{
}