这里我有两个类。如何让 JournalPage
调用 JournalEntryController
didSubmit
方法。
protocol JournalPageDelegate {
func didSubmit(for commentText: String)
}
class JournalPage: UIViewController, UITextViewDelegate {
var delegate: JournalPageDelegate?
fileprivate let textView: UITextView = {
let textView = UITextView()
let attributedText = NSMutableAttributedString(string: "Enter Text Here.", attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 18)])
textView.textColor = UIColor.black
textView.backgroundColor = UIColor.white
textView.becomeFirstResponder()
textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
textView.attributedText = attributedText
return textView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(save))
}
@objc func save() {
print("saving")
guard let commentText = textView.text else { return }
delegate?.didSubmit(for: commentText)
}
这是我要调用该方法的类。
class JournalEntryController: UIPageViewController, UIPageViewControllerDataSource, JournalPageDelegate {
func didSubmit(for commentText: String) {
print("Testing for text")
}
}
并且出于某种原因,当我在 JournalPage
类上点击保存时,我没有在控制台上看到“测试”。如何让 JournalPage
调用 JournalEntryController
didSubmit
方法?
最佳答案
无论何时使用委托(delegate),您都需要将该委托(delegate)从一个 View Controller 传递到另一个 View Controller 。 根据 Apple 定义:
委派是一种简单而强大的模式,其中程序中的一个对象委托(delegate)另一个对象或与另一个对象协作。委托(delegate)对象保留对另一个对象(委托(delegate))的引用,并在适当的时候向它发送消息。该消息通知委托(delegate)对象即将处理或刚刚处理的事件的委托(delegate)。委托(delegate)可以通过更新自身或应用程序中其他对象的外观或状态来响应消息,并且在某些情况下,它可以返回一个值来影响即将发生的事件的处理方式。委托(delegate)的主要值(value)在于它允许您轻松地在一个中心对象中自定义多个对象的行为。
你正在做的缺失部分是你没有为你在类 JournalEntryController
中调用 JournalTextDelegate
的例子调用委托(delegate),所以你需要调用这个 JournalTextDelegate
到您的 JournalPage
。
例如:假设你通过 push 方法转到另一个 View Controller
let vc = self.storyboard?.instantiateViewController(withIdentifier: “identifierier”) as! JournalPage
vc.delegate = self // you need to call this delegate
self.navigationController?.pushViewController(notifDetailVCObj, animated: true)
而且它会正常工作。有关引用,请参阅文档 https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html
关于ios - 根据控制台,委托(delegate)似乎没有工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52327377/