Here i have two classes. How do I make JournalPage
call JournalEntryController
didSubmit
method.
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)
}
And here is the class where I want to call the method.
class JournalEntryController: UIPageViewController, UIPageViewControllerDataSource, JournalPageDelegate {
func didSubmit(for commentText: String) {
print("Testing for text")
}
}
And for some reason, I don't see "Testing" on the console when I tap save on JournalPage
class. How do I make JournalPage
call JournalEntryController
didSubmit
method?
You delegate from pageview controller:
Whenever you used delegates you need to pass that delegate from one view controller to another view controller. According to Apple definition:
Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object–the delegate–and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.
The missing part you are doing is that you are not calling the delegate for expample you called
JournalTextDelegate
in your classJournalEntryController
so you need to call thisJournalTextDelegate
to yourJournalPage
.for example: Suppose your going to another view controller through push method
And it will work fine. For reference see documentation https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html