当我在UIView类中按下按钮时,我想触发navigationcontroller

时间:2019-03-28 12:37:45

标签: ios swift xcode uinavigationcontroller

当我按下UIView类中的按钮时,我想将导航控制器触发到其他屏幕。我怎样才能做到这一点?

//在其中创建按钮Iboutlet的UIView类的代码

import UIKit

protocol ButtonDelegate: class  {
    func buttonTapped()
}

class SlidesVC: UIView {

  var delegate: ButtonDelegate?

   @IBAction func onClickFinish(_ sender: UIButton) {

   delegate?.buttonTapped()

   }

   @IBOutlet weak var imgProfile: UIImageView!

    }

   //ViewController Class code in Which Button Protocol will be entertained

  class SwipingMenuVC: BaseVC, UIScrollViewDelegate {
         var  slidesVC = SlidesVC()

             override func viewDidLoad() {
                    super.viewDidLoad()

                    slidesVC = SlidesVC()
                    // add as subview, setup constraints etc
                    slidesVC.delegate = self

        }

extension BaseVC: ButtonDelegate {
  func buttonTapped() {

 self.navigationController?.pushViewController(SettingsVC.settingsVC(), 
            animated: true)

   }
   }

2 个答案:

答案 0 :(得分:0)

您可以使用委托模式来告诉包含在其中的ViewController该按钮已被按下,并让它处理下一步需要做的一切。该视图实际上不需要知道会发生什么。

一个基本示例:

protocol ButtonDelegate: class {
   func buttonTapped()
}

class SomeView: UIView {
    var delegate: ButtonDelegate?

    @IBAction func buttonWasTapped(_ sender: UIButton) {
        delegate?.buttonTapped()
    }
}

class ViewController: UIViewController {
    var someView: SomeView

    override func viewDidLoad() {
       someView = SomeView() 
       // add as subview, setup constraints etc
       someView.delegate = self
    } 
}

extension ViewController: ButtonDelegate {
    func buttonTapped() {
        self.showSomeOtherViewController() 
        // or 
        let vc = NewViewController()
        present(vc, animated: true) 
    }
}

答案 1 :(得分:0)

一种更简单的方法是使用typealias。您必须在2个地方编写代码。 1.您的viewClass和2.在您的View Controller中。

在SlidesView类中添加类型别名,并在需要时定义参数类型,否则将其留空。

class SlidesView: UIView {
typealias OnTapInviteContact = () -> Void
var onTapinviteContact: OnTapInviteContact?

    @IBAction func buttonWasTapped(_ sender: UIButton) {
    if self.onTapinviteContact != nil {
      self.onTapinviteContact()
    }

  }
}

  class SwipingMenuVC: BaseVC, UIScrollViewDelegate {
             override func viewDidLoad() {
                    super.viewDidLoad()

                    let slidesView = SlidesView()
                    slidesView.onTapinviteContact = { () in
                    // do whatever you want to do on button tap
            }

        }