swift - 没有 Storyboard或转场的委托(delegate)模式

标签 swift delegates viewcontroller

我正在学习对委托(delegate)模式有一个扎实的理解。 iOS 中的很多代码示例都使用两个 ViewController,其中涉及 prepare(for segue:...)

我希望我的程序仅使用一个带有委托(delegate)协议(protocol)的ViewController,但不使用segue 或storyboard。 ViewController 有一个按钮来执行一个简单的委托(delegate)方法,比如说添加一个数字。

ViewController 类:

class ViewController: UIViewController, theDelegate {

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

// It is here I got stuck
// How do I set delegate = self without out involving segue or the     storyboard at all? Do I need to instantizate the dedecated delegate class and how?
// To conform to delegate -- theDelegate
func add(num: Int) {
    // Output result on ViewController
}

func minus(num: Int) {
    // Output result on ViewController
}
}

专用的Delegate类:

protocol theDelegate: class {
func add(num: Int)
func minus(num: Int)
}

class ClassDelegate: NSObject {
weak var delegate: theDelegate?

func x() {
    delegate?.add(num: 100)
}
}

最佳答案

如果您的 View Controller 是委托(delegate),那么您的类命名会很困惑。您所说的 ClassDelegate 不会是任何类型的委托(delegate),而是使用委托(delegate)的“Worker”。然而....

var worker = ClassDelegate()
override func viewDidLoad() {
    super.viewDidLoad()
    worker.delegate = self
    worker.x()
}

关于swift - 没有 Storyboard或转场的委托(delegate)模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44700306/

相关文章:

swift - 使用未解析的标识符 'zombies'

macos - PresentedViewControllers 内存泄漏

ios - 与 UIScrollView 结合使用时 UIPageControl 不可见

ios - 如何在swift4中从json数组获取值

ios - Swift App Xib - 第二个 ViewController - 标签未显示 30 秒,但按钮等显示。我该如何解决?

c# - 无法将 lambda 表达式转换为类型 'object',因为它不是委托(delegate)类型

ios - 在扩展中的弱属性上添加 didSet 观察者

c# - IEnumerable 类中的委托(delegate)列表<T>

ios - 对 segue 源 View Controller 的引用

swift - 使用 UserDefaults 在 Swift 中保存自定义对象的字典