【问题标题】:Delegate Pattern In Swift w/o Segue没有 Segue 的 Swift 中的委托模式
【发布时间】:2018-04-13 02:03:50
【问题描述】:

如果没有包含 segue,我找不到 Swift 委托模式的示例。我希望老板类(老板视图)向工人阶级(工人视图)发送订单并打印老板说要打印的内容。当我按下老板页面上的任一按钮(doThisButton/doThatButton)时,代表将出现“零”。

编辑:我的视图设置如下:“TheBoss”VC 有三个按钮,“doThisButton”、“doThatButton”和“goToTheWorker”按钮。 'TheWorker' VC 有一个文本框。 'doThisButton'/'doThatButton' 将信息发送到 'TheWorker' VC 中的文本框,但不会使 'TheWorker' VC 出现。 “goToTheWorker”按钮是在情节提要中设置的用于打开“TheWorker”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
    }
}

【问题讨论】:

  • Worker VC 是如何创建和呈现的?还是Boss VC?哪个是第一个,它们是如何连接的?
  • 两者都嵌入在导航控制器中,老板首先出现并包含一个按钮,该按钮通过 show segue 连接到工作人员。
  • 等等,什么?老板装箱工人?那为什么你的TheWorker 类中有代码来创建一个新的 theBoss 实例?这没有任何意义。
  • 您的问题和您的 cmets 相互矛盾。您需要更清楚地描述您的问题,否则我们无法帮助您。

标签: ios swift xcode delegates


【解决方案1】:

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

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 连接到工人。什么?你说的很清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多