没有故事板或segue的委托模式
问题描述:
我正在学习对委托模式的深入了解。 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)
}
}
答
如果您的视图控制器是委托,那么你的类命名是混乱的。你所说的ClassDelegate
不会是任何类型的代表,而是使用代表的“工人”。但是....
var worker = ClassDelegate()
override func viewDidLoad() {
super.viewDidLoad()
worker.delegate = self
worker.x()
}
谢谢大家的回复。 @PhillipMills我不是很确定你的意思,你是说我没有正确使用委托模式? – Tony