我正在学习对委托(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/