在Swift中使用多个视图控制器

时间:2016-04-02 16:44:54

标签: ios swift uiviewcontroller

我正在以编程方式开发一个非常简单的Swift应用程序(没有故事板)。我有一个HomeViewController

import UIKit

class HomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func createButton(){

        let button = UIButton()
        button.setTitle("Start", forState: .Normal)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button.frame = CGRectMake(100,200,50,50)
        button.addTarget(self, action: "timerPressed:", forControlEvents: .TouchUpInside)
        self.view.addSubview(button)

    }

}

我有以下

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let home = HomeViewController()
        home.createButton()
    }

}

当我打电话给home.createButton()时,我希望显示一个按钮,但目前却没有。我知道该方法有效,因为当我将createButton()方法移动到ViewController类时,它会显示该按钮。我错过了如何从HomeViewController中正确调用createButton方法。做我想做的事情会有更好的约定吗?

2 个答案:

答案 0 :(得分:1)

    class func createButton(controller: UIViewcontroller){

            let button = UIButton()
            button.setTitle("Start", forState: .Normal)
            button.setTitleColor(UIColor.blueColor(), forState: .Normal)
            button.frame = CGRectMake(100,200,50,50)
            button.addTarget(self, action: "timerPressed:", forControlEvents: .TouchUpInside)
            controller.view.addSubview(button)

        }

现在将此方法调用到任何ViewController

喜欢这个:

  

HomeViewController.createButton(个体)。

答案 1 :(得分:0)

您可以在HomeViewController的 loadview()方法下编写 createButton 代码

class HomeViewController: UIViewController {

  override func loadView() {
        super.loadView()
        let button = UIButton()
        button.setTitle("Start", forState: .Normal)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button.frame = CGRectMake(100,200,50,50)
        button.addTarget(self, action: "timerPressed:", forControlEvents: .TouchUpInside)
        self.view.addSubview(button)
    }
}

因此无需调用 HomeViewController 的额外方法来添加按钮作为其子视图。