我正在學習對委託模式的深入瞭解。 iOS中的很多代碼示例使用了兩個ViewControllers
,其中涉及prepare(for segue:...)
。沒有故事板或segue的委託模式
我希望我的程序只使用一個ViewController
與代表協議,但沒有segue或故事板。 ViewController
有一個按鈕來執行簡單的委託方法,比方說添加一個數字。
的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)
}
}
謝謝大家的回覆。 @PhillipMills我不是很確定你的意思,你是說我沒有正確使用委託模式? – Tony