如何从另一个视图控制器设置按钮的操作

问题描述 投票:2回答:5

如何创建可重用的视图控制器(让我们称之为“reusableVC”),就像UIAlertController一样。 ReusableVC有“ok”按钮,它将取决于resuableVC所调用的位置。我知道代表和NotificationCenter。只是想知道我们可以在创建reusableVC时传递“ok”按钮应该做什么,如下所示:

reusableVC.addAction(UIAlertAction(title: "", style: .default, handler: { (action) in
   // some code
}))
ios swift
5个回答
2
投票

如果您只需要一个OK按钮,则可以使用此解决方案,否则,您仍然可以对此模式感兴趣。

class ReusableVC{
    var onOKPressed: ( () -> () )?

    // Create all your other things and don't forget that you should call onOKPressed() whenever user pushed that OK button
}

class ViewController{

    func setupReusableVC(){

        let reusableVC = ReusableVC()
        reusableVC.onOKPressed = {
            print("ok pressed")
        }
    }
}

1
投票

动作处理程序只是一个闭包。你可以在任何地方声明它。


在可重用视图控制器中添加属性

var customAction : ((UIAlertAction) -> Void)?

并将属性作为处理程序传递

reusableVC.addAction(UIAlertAction(title: "", style: .default, handler: customAction))

在源视图控制器中创建操作

let action : ((UIAlertAction) -> Void)? = { action in 
    // do something
}

并传递给perform(segue


0
投票

Create a UIViewController Extension to include Alert Functionality

extension UIViewController{
    open func hideKeyBoardOnTap(){
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        self.view.addGestureRecognizer(tap)
    }

    @objc private func dismissKeyboard(){
        self.view.endEditing(true)
    }

    open func showAlertWithOK(_ title: String = "Alert!",message: String = "Please take appropriate action"){
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okButton = UIAlertAction(title: "Ok", style: .default, handler:{ (alertAction) in
            self.okAction()
        })
        alert.addAction(okButton)
        DispatchQueue.main.async {
            self.present(alert, animated: true, completion: nil)
        }
    }

    open func showAlertWithOkAndCancel(_ title: String = "Alert!",_ message: String = "Please take appropriate action", _ firstButtonTitle: String = "Ok", _ firstButtonStyle: UIAlertActionStyle = .default, _ secondButtonTitle: String = "Cancel",_ secondButtonStyle: UIAlertActionStyle = .cancel){
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okButton = UIAlertAction(title: firstButtonTitle, style: firstButtonStyle, handler:{ (alertAction) in
            self.okAction()
        })
        let cancelButton = UIAlertAction(title: secondButtonTitle, style: secondButtonStyle, handler: { (alertAction) in
            self.cancelAction()
        })
        alert.addAction(okButton)
        alert.addAction(cancelButton)
        self.present(alert, animated: true, completion: nil)
    }

    @objc private func okAction(){
        self.dismiss(animated: true, completion: nil)
    }

    @objc private func cancelAction(){
        self.dismiss(animated: true, completion: nil)
    }
}

How to Use

func didReceiveError(_ error: CFNetworkErrors) {
    var message = error.message
    self.showAlertWithOK("Error", message: message)
}

func didEndWebserviceCall() {
    self.showAlertWithOK(message: "didEndWebserviceCall")
}

Advantages:

  1. 您可以使用self访问警报(在这种情况下,您的viewcontroller)
  2. 代码可重用性
  3. 清洁代码。

0
投票
protocol TapEventDelegate: protocol {
func buttonTap()
}

class ClassWhereDoYouWantToCatchTheEvent: TapEventDelegate {
func buttonTap() {
print("caught!")
}
 }

class YourViewControllerClass {
weak var tapEventDelegate: TapEventDelegate?
reusableVC.addAction(UIAlertAction(title: "", style: .default, handler: { (action) in
   tapEventDelegate?.buttonTap()
}))
}

YourViewControllerClassClassWhereDoYouWantToCatchTheEvent绑定你的类在视图控制器初始化时使用某处:

classWhereDoYouWantToCatchTheEvent.tapEventHandler = yourViewControllerClass

0
投票

您可以创建自定义UIViewController类并传递addAction closure,然后您可以在CustomAlertController的OK按钮上调用该闭包。

final class CustomAlertController: UIViewController {

    var actionHandler: (() -> Void)?

    lazy var okButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = .black
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("OK", for: .normal)
        button.addTarget(self, action: #selector(CustomAlertController.didTapOkButton(_:)), for: .touchUpInside)
        button.layer.cornerRadius = 10
        return button
    }()

    override func loadView() {
        view = UIView()
        view.backgroundColor = .white
    }

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

    private func addActionButton() {
        view.addSubview(okButton)
        NSLayoutConstraint.activate([
            okButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50),
            okButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -50),
            okButton.heightAnchor.constraint(equalToConstant: 50),
            okButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 100)
        ])
    }

    public func addAction(title: String, handler: @escaping (() -> Void) {
        okButton.setTitle(title, for: .normal)
        actionHandler = handler
    }

    @objc func didTapOkButton(_ button: UIButton) {
        actionHandler?()
        dismiss(animated: true)
    }
}

然后你可以从你的CustomAlertController类中展示ViewController并添加如下所示的动作

class ViewController: UIViewController {

    override func loadView() {
        view = UIView()
        view.backgroundColor = .white
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let alertController = CustomAlertController()
        alertController.addAction(title: "OK", handler: { [unowned self] in
            self.view.backgroundColor = .blue
            print("OK button tapped")
        })
        present(alertController, animated: true)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.