将具有屏幕视图的另一个类的委托设置为self

时间:2015-08-30 18:49:46

标签: swift delegates protocols

我在iOS编程方面相当新。我有这个设置:

{p> mapLayer查看IB,课程ViewController

{p> ViewController查看IB,课程SecondController

我有协议:

secondController

我在SecondController上有委托变量:

protocol SecondControllerDelegate {
    func getSomething() -> String
}

现在,根据各处的提示,为了让我可以在class secondController: UIViewController { var delegate: SecondControllerDelegate? @IBOutlet weak var labelStatus: UILabel! override func ViewDidLoad() { super.viewDidLoad() } @IBAction func buttonTouch(sender: AnyObject) { labelStatus.text = delegate?.getSomething() } func try () { labelStatus.text = "testing" } } 调用delegate?.getSomething(),我需要在viewController上设置如下:

SecondController.buttonTouch()

但这会产生错误class ViewController: UIViewController, SecondControllerDelegate { override func viewDidLoad () { super.viewDidLoad() SecondController.delegate = self } func doSomething () -> String { return "testing" } }

其他一些网站说:

'SecondController.type' does not have a member named 'delegate'

有了这个,就没有错误。但是如果我在应该调用委托的第二个屏幕上执行某些操作,它就不会调用委托,就像SecondController是两个不同的对象(一个是由StoryBoard创建的,一个是在ViewController中手动创建的),即class ViewController: UIViewController, SecondControllerDelegate { var secondController = SecondController() override func viewDidLoad () { super.viewDidLoad() secondController.delegate = self } func doSomething () -> String { return "testing" } } 应该更改为"测试",根本不会发生变化。但是如果调用函数labelStatus,它会改变。我该怎么做?

编辑:我忘了提到我使用了NavigationController,并且从第一个屏幕过渡到第二个屏幕。

1 个答案:

答案 0 :(得分:4)

因为您尝试学习如何在Swift中构建委托,所以我在下面写了一个简单的委托示例

protocol SecondViewControllerDelegate {
    func didReceiveInformationFromSecondViewcontroller (information: String)
}

class ViewController: UIViewController, SecondViewControllerDelegate {

    func openSecondViewController () {
        if let secondViewControllerInstance: SecondViewController = storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as? SecondViewController {
            secondViewControllerInstance.delegate = self
            navigationController?.pushViewController(secondViewControllerInstance, animated: true)
        }
    }

    func didReceiveInformationFromSecondViewcontroller(information: String) {
        ////Here you get the information, after sendInfoToViewController() has been executed
    }

}


class SecondViewController: UIViewController {

    var delegate: SecondViewControllerDelegate?

    func sendInfoToViewController () {
        delegate?.didReceiveInformationFromSecondViewcontroller("This ist the information")
    }

}

<强>更新

在使用Storyboard Segues时采用相同的方法

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if let secondViewControllerInstance: SecondViewController = segue.destinationViewController as? SecondViewController {
            secondViewControllerInstance.delegate = self
        }
    }