代表模式在Swift没有Segue

时间:2018-04-13 02:03:50

标签: ios swift xcode delegates

我没有找到包含segue的Swift Delegate模式的示例。我希望老板类(老板视图)向工人类(工人视图)发送订单并打印老板说打印的内容。代表即将到来' nil'当我按下boss页面上的任一按钮(doThisButton / doThatButton)时。

编辑:我的观看次数设置如下:' TheBoss' VC有三个按钮,' doThisButton'' doThatButton'和' goToTheWorker'按钮。 ' TheWorker' VC有一个文本框。 ' doThisButton' doThatButton'将信息发送到' TheWorker'中的文本框VC,但不要让工作者' VC出现了。 ' goToTheWorker'按钮是在故事板中设置的show segue,用于打开“工作人员”按钮。 VC

这是老板'类

import UIKit

protocol TheBossesOrdersDelegate {
    func doThis(numberOne: Int, stringOne: String)
    func doThat(numberTwo: Int, stringTwo: String)
}

class TheBoss: UIViewController {

    // Declair Delegate
    var delegate: TheBossesOrdersDelegate!

    @IBAction func doThisButton(_ sender: UIButton) {
        delegate.doThis(numberOne: 75, stringOne: "Do This")
    }
    @IBAction func doThatButton(_ sender: UIButton) {
        delegate.doThat(numberTwo: 125, stringTwo: "Do That")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

这是'工人'类

import UIKit

class TheWorker: UIViewController, TheBossesOrdersDelegate {

    let theBoss = TheBoss()

    func doThis(numberOne: Int, stringOne: String) {
        print("the boss send this number to print: \(numberOne) and this string: \(stringOne)")
        theWorkersTextBox.text = "Number: \(numberOne) String:\(stringOne)"
    }

    func doThat(numberTwo: Int, stringTwo: String) {
        print("the boss send this number to print: \(numberTwo) and this string: \(stringTwo)")
        theWorkersTextBox.text = "Number: \(numberTwo) String:\(stringTwo)"
    }

    @IBOutlet weak var theWorkersTextBox: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        theBoss.delegate = self
    }
}

1 个答案:

答案 0 :(得分:0)

看起来你的代码让工人创建了老板。既然你这样做,你需要告诉老板他的代表是谁:

import UIKit

class TheWorker: UIViewController, TheBossesOrdersDelegate {


    let theBoss = { 
      let result = TheBoss()
      result.delegate = self  //This is the line you are missing
      return result
    }()

//The rest of your TheWorker class's code...
}

编辑:

根据你的评论,你有一个混乱的混乱。发布显示工作视图控制器的按钮的Boss类代码。你的标题是" w / o segue",然后在你的评论中你说"老板首先出现并包含一个通过show segue连接到工人的按钮&#34。什么?你说没有塞弗。