ios - 在 Swift 中使用多个 View Controller

标签 ios swift uiviewcontroller

我正在以编程方式开发一个非常简单的 Swift 应用程序(没有 Storyboard)。我有一个 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 方法的内容。有没有更好的约定来完成我想做的事情?

最佳答案

    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(self).

关于ios - 在 Swift 中使用多个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375991/

相关文章:

objective-c - Xcode - 何时使用 UIView 或 UITableView?

ios - 尝试使用前向类 UIViewController

ios - 枚举对象并将其添加到 NSMutableSet 时的 exc_bad_access

ios - 我可以在 iOS App 中本地存储 JSON 文件吗

ios - 崩溃报告 - iOS - 与 View Controller 相关?

ios - Swift UIActivityViewController Image&Url Share 不适用于 FB

ios - Swift 中根据属性删除数组对象

iphone - 滑动即可更改 View

ios - WebCamTexture iOS 模糊快照

ios - 通过 segue 传递数据库数据