简体   繁体   English

我如何从 UIView 转到 UIViewController 故事板

[英]How can i goto UIViewController storyboard from UIView

UIView界面视图

import UIKit

class TridHeaderBar: UIView {


    @IBAction func btnClick(_ sender: Any) {

    }

}

I would like to go a ViewController from this UIView.我想从这个 UIView 去一个 ViewController。 I have tried below code我试过下面的代码

let ctrl = FirstViewController()
self.present(ctrl, animated: true, completion: nil)

You can use various methods to reach your goal, one of them(and one the best) is use delegation .您可以使用各种方法来实现您的目标,其中一种(也是最好的一种)是使用delegate

So first you need to define your delegate:所以首先你需要定义你的委托:

protocol MYViewDelegate: class {
  func buttonTap(sender: MYView)
}

Then in your view:那么在你看来:

class MyView: UIView {
    weak var delegate: MYViewDelegate?

    @IBAction func btnClick(_ sender: Any) {
        delegate?.buttonTap(sender: self)
    }
}

Now you set the parent view controller where you custom view as delegate of you custom view and the job is done.现在,您将自定义视图的父视图控制器设置为自定义视图的委托,工作就完成了。

class MYParentViewController: UIViewController {
    @IBOutlet var myCustomView: MyView!

    override func viewDidLoad() {
       super.viewDidLoad()
       myCustomView.delegate = self
    }
}

extension MYParentViewController: MYViewDelegate {
    func buttonTapped(sender: MYView) {
       let ctrl = FirstViewController()
       self.present(ctrl, animated: true, completion: nil)
    }
}

You can use Callback function also to get tap action on your parrentViewController:您还可以使用回调函数在您的 parrentViewController 上获取点击操作:

1) Declare callback function into your view: 1)在您的视图中声明回调函数:

var callback:(() -> Void)?

You can also pass any value from your view like (var callback:((String) -> Void)?).您还可以从您的视图中传递任何值,例如 (var callback:((String) -> Void)?)。 I take string here you can pass as you want.我在这里拿绳子,你可以随意传递。

and in button action call this function like this (callback?("i am passing string here"))并在按钮操作中像这样调用这个函数(回调?(“我在这里传递字符串”))

2) Call this function in your IBAction of button: 2) 在你的 IBAction 按钮中调用这个函数:

@IBAction func btnClick(_ sender: Any) {
     callback?()
}

3) Write callback function closure in your parrentViewControler: 3) 在你的 parrentViewControler 中编写回调函数闭包:

class ParentViewController: UIViewController {
    @IBOutlet var myCustomView: MyView!

    override func viewDidLoad() {
       super.viewDidLoad()
       viewTapped()
    }

   func viewTapped() {
      myCustomView.callback = { [unowned self] 
          //you will get button tap action here
          let ctrl = FirstViewController()
          self.present(ctrl, animated: true, completion: nil)
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM