Using custom view in alert with Swift

时间:2016-07-11 20:29:55

标签: ios swift uiview uinavigationcontroller uialertcontroller

How can I make an alert containing custom view which contains a uitableview?

UserInteraction should be disabled everywhere in the background. As soon as a row gets selected, the alert window should disappear.

let popup : PopupVC = self.storyboard?.instantiateViewControllerWithIdentifier("PopupVC") as! PopupVC
let navigationController = UINavigationController(rootViewController: popup)
navigationController.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
self.presentViewController(navigationController, animated: true, completion: nil)

And this gives no errors but showing a different view with no interaction.

2 个答案:

答案 0 :(得分:0)

It's not possible to modify the default UIAlertController. But you can use for example SDCAlertView. This basically creates custom UIAlertControllers that look exactly like the built-in, but you can edit the content view.

Example (copied from the Readme):

let spinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
spinner.translatesAutoresizingMaskIntoConstraints = false
spinner.startAnimating()

let alert = AlertController(title: "Title", message: "Please wait...")
alert.contentView.addSubview(spinner)

spinner.centerXAnchor.constraintEqualToAnchor(alert.contentView.centerXAnchor).active = true
spinner.topAnchor.constraintEqualToAnchor(alert.contentView.topAnchor).active = true
spinner.bottomAnchor.constraintEqualToAnchor(alert.contentView.bottomAnchor).active = true

alert.present()

You can basically add everything as subview of alert.contentView

答案 1 :(得分:-1)

No, it is not possible to replace the UIAlertController behavior, but you can extend it:

extension UIAlertController {
    static func showCustomAlert() {

    }

    static func showCustomAlert(data: [AnyObject]) {

    }
}

Within the first function you can call your custom view controller. And within the second you can pass some data to it, for example when your custom view controller shows a table view that needs data to show.

So when you need to show the alert you just can do:

UIAlertController.showCustomAlert()

Note that the static keyword allows you to call the function without creating an instance of UIAlertController.