在不同的ViewControllers中使用相同的UIAlertController

时间:2017-07-18 08:38:57

标签: swift swift3 swrevealviewcontroller

我使用了侧面导航菜单(SWReveal)。我有4个ViewControllers。如何在不同的视图中使用相同的alertAction。

6 个答案:

答案 0 :(得分:0)

  1. 使用可以显示警报的方法创建 BaseController

     //Copyright © 2017 dip. All rights reserved.
    
    import UIKit
    
    class BaseController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    ///This is common method to show alert with same action 
    func showAlert() {
        let alert = UIAlertController(title: "Alert", message: "my msg on alert", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            ///This will be common alert ok aciton for all child controllers.
            print("Do some userful common work..")
    
        }))
    
          self.present(alert, animated: true, completion: nil)            
      }
    }
    
  2. 继承 BaseController

    中的4个控制器
     //  Copyright © 2017 dip. All rights reserved.
    //
    
    import UIKit
    
    class ChildVC: BaseController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //call show alert when ever you wish 
            ///This method will call showAlert() method on super class (BaseController)
            self.showAlert()
    
        }
       }
    
    1. 当您希望通过常规操作显示提醒时,请从子级调用self.showAlert()方法。

答案 1 :(得分:0)

您可以创建UIViewController扩展名,如下所示:

extension UIViewController {
    func showAlert(title: String?, message: String?, actionTitles:[String?], actions:[((UIAlertAction) -> Void)?]) {
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            for (index, title) in actionTitles.enumerated() {
                let action = UIAlertAction(title: title, style: .default, handler: actions[index])
                alert.addAction(action)
            }
            self.present(alert, animated: true, completion: nil)
        }
    }

您可以在UIViewController中使用此提醒,如下所示:

    showAlert(title: "Your Title", message: "Your custom Message", actionTitles: ["Ok","Cancel"], actions: [{ action1 in
                   //OK Action
                }, { action2 in
                    // Cancel Action
                }
           ])

希望能得到你的解决方案。

答案 2 :(得分:0)

您也可以这样使用。

// CustomComponent.js

import React, { Component } from 'react'
import { Text } from 'react-native'
import BaseComponent from './BaseComponent'

export default class CustomComponent extends Component {

  getView() {
    return(
      <Text> Hello { this.props.name }! </Text>
    )
  }

  render() {
    <BaseComponent contentView={ this.getView.bind(this) }>
  }
}

并在下面的示例中使用add添加

class IOSPublicDefaultAlert: NSObject{

    var viewController: UIViewController?
    var actionCompletion: ((String) -> ())?
    var alertTitle: String?
    var alertMessage : String?
    var alertType: UIAlertControllerStyle?
    var actionTitleAndType: [String: UIAlertActionStyle]?



    init(viewController : UIViewController,alertTitle: String?,alertMessage : String?,alertType: UIAlertControllerStyle = .alert,actionTitleAndType: [String: UIAlertActionStyle] ,actionCompletion :  ((String)->())?){

        super.init()
        self.viewController = viewController
        self.actionCompletion = actionCompletion
        self.alertTitle = alertTitle
        self.alertMessage = alertMessage
        self.alertType = alertType
        self.actionTitleAndType = actionTitleAndType

        showAlert()
    }


    func showAlert(){

        let alert = UIAlertController.init(title: alertTitle, message: alertMessage, preferredStyle: self.alertType ?? .alert)

        for (actionTitle, actionType) in actionTitleAndType!{

            let action = UIAlertAction(title: actionTitle, style: actionType) { (action) in

                if let com = self.actionCompletion{

                    com(actionTitle)
                }
            }
            alert.addAction(action)
        }

        viewController?.present(alert, animated: true, completion: nil)
    }
}

答案 3 :(得分:0)

在swift,您的项目中,您可以创建一个新的.swift文件,并在此文件中创建一个类:

import UIKit
import Foundation

class yourFileName {

    //Create a class function alerview
    class func displayAlert(title: String, withMessage msg: String, andbtnTitle btntitle: String, in vc: UIViewController) {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: btntitle, style: UIAlertActionStyle.default, handler: nil))

        appDelegate.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }
}

//and now your any ViewController.swift file or any other file in your project you can access alert following way.
class viewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        yourfilename.displayAlert(title: "Alert", withMessage msg: "my alert view display", andbtnTitle btntitle: "Ok", in vc: self) // access your alertview
    }
}

我希望它适合你。

答案 4 :(得分:0)

// MARK: - Alertable View

protocol AlertableView {

    // Use handler if need catch cancel alert action
    typealias CompletionHandler = (() -> Void)

    func displayAlert(with title: String, message: String, actions: [UIAlertAction]?)
    func displayAlert(with title: String, message: String, style: UIAlertControllerStyle, actions: [UIAlertAction]?, completion: CompletionHandler?)
}

extension AlertableView where Self: UIViewController {

    func displayAlert(with title: String, message: String, actions: [UIAlertAction]?) {
        self.displayAlert(with: title, message: message, style: .alert, actions: actions, completion: nil)
    }

    func displayAlert(with title: String, message: String, style: UIAlertControllerStyle, actions: [UIAlertAction]?, completion: CompletionHandler?) {

        let alertCancelAction = UIAlertAction(title: "Cancel".localized, style: .cancel) { (action) in

            guard let completion = completion else { return }
            completion()
        }

        let alertController = UIAlertController(title: title, message: message, preferredStyle: style)

        if let actions = actions {

            for action in actions {
                alertController.addAction(action)
            }

            alertController.addAction(alertCancelAction)

        } else {

            // If not any custom actions, we add OK alert button

            let alertOkAction = UIAlertAction(title: "OK".localized, style: .cancel) { (action) in

                guard let completion = completion else { return }
                completion()
            }

            alertController.addAction(alertOkAction)
        }

        self.present(alertController, animated: true, completion: nil)
    }

}

答案 5 :(得分:-1)

创建一个通用函数

import UIKit

class AlertClass: NSObject {

    func showAlertWithVC(_ VC : UIViewController, andMessage message: String ){
        DispatchQueue.main.async {
            let alert = UIAlertController(title: "APPLICATION_NAME", message: message , preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            VC.present(alert, animated: true, completion: nil)
        }
    }
}

只需调用AlertClass()。showAlertWithVC(),即可显示警报。