-
Notifications
You must be signed in to change notification settings - Fork 1
/
NoteViewController.swift
81 lines (58 loc) · 2.89 KB
/
NoteViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// NoteViewController.swift
// Notes
//
// Created by Julian Moorhouse on 15/08/2019.
// Copyright © 2019 Mindwarp Consultancy Ltd. All rights reserved.
//
import UIKit
class NoteViewController: UIViewController {
var note: Note?
var didUpdateItem: ((_ item: Note) -> Void)?
var didDeleteItem: ((_ item: Note) -> Void)?
@IBOutlet var textField: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = false
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
navigationItem.rightBarButtonItems = [share]
textField.text = note?.content
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
let delete = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deleteNote))
setToolbarItems([delete], animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let thisNote = self.note {
thisNote.content = textField.text
didUpdateItem?(thisNote)
}
}
@objc func deleteNote() {
if let thisNote = self.note {
didDeleteItem?(thisNote)
}
navigationController?.popViewController(animated: true)
}
@objc func adjustForKeyboard(notification: Notification) {
guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardScreenEndFrame = keyboardValue.cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == UIResponder.keyboardWillHideNotification {
textField.contentInset = .zero
} else {
textField.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height - view.safeAreaInsets.bottom, right: 0)
}
textField.scrollIndicatorInsets = textField.contentInset
let selectedRange = textField.selectedRange
textField.scrollRangeToVisible(selectedRange)
}
@objc func shareTapped() {
let vc = UIActivityViewController(activityItems: [textField.text ?? ""], applicationActivities: [])
vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
present(vc, animated: true)
}
}