为同一个 ViewController 使用不同的 swift 文件? [英] Use different swift files for same ViewController?

查看:26
本文介绍了为同一个 ViewController 使用不同的 swift 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中的布局保持不变,除了图像会有所不同,具体取决于在前一个视图中按下的按钮.我想要做的是将其设置为如果按下 btn1 将用户带到下一个视图,然后使用 VCfile1.swift 并且如果用户按下 btn2 那么他将被带到下一个视图并使用 VCFile2.swift对于在故事板中创建的同一个视图控制器.我怎么能做到这一点?(我不确定这是正确的方法,但如果不是,请提出建议)

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

Swift 3, Xcode 8

推荐答案

第一:如果你需要 100 个 UViewControllers,它们都具有相同的视图,那么你做错了什么.

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

要在不同的 ViewController(.swift) 类中重复使用相同的视图,您可能需要将 UIView 创建为 XIB 并(重新)在您的以编程方式查看控制器.

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:

类 MyView:UIView {//}

class MyView: UIView { // }

创建一个XIB文件(new -> file -> View)MyView.xib,将它的类设置为MyView和根据您的需要进行定制.

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

创建一个实例并在您的 UIViewControllers 中使用它:

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
    }
}

这篇关于为同一个 ViewController 使用不同的 swift 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆