Use different swift files for same ViewController?

2019-05-29 13:45发布

I've got a layout in my app that stays the same besides the images which will differ depending on what button is pressed in the previous view. What I was thinking to do is set it to that if btn1 is pressed the user it taken to the next view but then VCfile1.swift is used and if the user presses btn2 then he is taken to the next view and VCFile2.swift is used for the same viewcontroller created in the storyboard. How could I achieve this? (I'm not sure I this is the correct method but if not please do advise)

Swift 3, Xcode 8

1条回答
霸刀☆藐视天下
2楼-- · 2019-05-29 14:45

First: If you need 100 UViewControllers, all with the same view, your doing something wrong.

To re-use the same View in different ViewController(.swift) classes you may want tocreate your UIView as a XIB and (re-)use it in your ViewControllers programmatically.

  • Create a class for your view:

    class MyView: UIView { // }

  • Create a XIB file (new -> file -> View) MyView.xib, set its class to MyView and customize it to your needs.

  • Create an instance and use it in your UIViewControllers:

    class MyViewController: UIViewController {
        var myView: MyView?
    
        override func viewDidLoad() {
            super.viewDidLoad()
            myView = UINib(nibName: "MyView", bundle: nil).instantiate(withOwner: self, options: nil).first as? MyView
            view.addSubview(myView!)
            // You might want to set constraints here
        }
    }
    
查看更多
登录 后发表回答