質問するログイン新規登録

質問編集履歴

1

こーどの追加

2020/03/23 05:15

投稿

Ytan
Ytan

スコア39

title CHANGED
File without changes
body CHANGED
@@ -9,11 +9,238 @@
9
9
  ログインしなおしてもそのまま削除した状態にするにはどのような継承をすればいいですか?
10
10
 
11
11
  ```Swift
12
+ import UIKit
13
+ import ChameleonFramework
14
+ import Firebase
15
+
16
+
17
+ class ChatViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {
18
+
19
+
20
+
21
+ @IBOutlet weak var tableView: UITableView!
22
+ @IBOutlet weak var messageTextField: UITextField!
23
+ @IBOutlet weak var sendButton: UIButton!
24
+
25
+ //スクリーンのサイズ
26
+ let screenSize = UIScreen.main.bounds.size
27
+
28
+
29
+ var chatArray = [Message]()
30
+
31
+ override func viewDidLoad() {
32
+ super.viewDidLoad()
33
+
34
+ tableView.delegate = self
35
+ tableView.dataSource = self
36
+ messageTextField.delegate = self
37
+
38
+ //セルを反映
39
+ tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "Cell")
40
+ //行の高さを可変
41
+ tableView.rowHeight = UITableView.automaticDimension
42
+ //見積もりの高さ
43
+ tableView.estimatedRowHeight = 75
44
+
45
+ //キーボード開く時
46
+ //NotificationCenterに反応がおこった場合こったどれが呼ばるか
47
+ //keyboardWillShowNotification時にkeyboardWillShow(メソッドが呼ばれる)
48
+ NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.keyboardWillShow(_ :)), name: UIResponder.keyboardWillShowNotification, object: nil)
49
+
50
+ //キーボード閉じる時
51
+ NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.keyboardWillHide(_ :)), name: UIResponder.keyboardWillHideNotification, object: nil)
52
+
53
+ //Firebaseからデータをfetchしてくる
54
+ fetchChatData()
55
+
56
+ //tableViewのセルの線を消す
57
+ tableView.separatorStyle = .none
58
+
59
+
60
+ }
61
+
62
+
63
+ //引数としてNSNotification型が取れる
64
+ //#selectorはobjectCの名残だから@objc
65
+ //notificationは上の情報を持っている
66
+ @objc func keyboardWillShow(_ notification:NSNotification){
67
+
68
+ //キーボードと一緒にViewも上げる方法
69
+ //cgRectValue端末ごとの高さを取得
70
+ let keyboardHeight = ((notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as Any) as AnyObject).cgRectValue.height
71
+
72
+ messageTextField.frame.origin.y = screenSize.height - keyboardHeight - messageTextField.frame.height
73
+
74
+ }
75
+
76
+ @objc func keyboardWillHide(_ notification:NSNotification){
77
+
78
+ messageTextField.frame.origin.y = screenSize.height - messageTextField.frame.height
79
+
80
+ //キーボード全般の大きさを取得
81
+ guard let rect = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue,
82
+
83
+ //guardとして並行している
84
+ //キーボードが下がる時間をdurationとして取得
85
+ let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else{return}
86
+
87
+
88
+ UIView.animate(withDuration: duration){
89
+
90
+ let transform = CGAffineTransform(translationX: 0, y: 0)
91
+ self.view.transform = transform
92
+
93
+ }
94
+
95
+ }
96
+
97
+ //buttonをタッチした場合に起こる
98
+ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
99
+
100
+ messageTextField.resignFirstResponder()
101
+
102
+ }
103
+
104
+ //textFieldを閉じる方法
105
+ func textFieldShouldReturn(_ textField: UITextField) -> Bool {
106
+
107
+ textField.resignFirstResponder()
108
+ return true
109
+
110
+ }
111
+
112
+
113
+
12
- //cellをスワイプで削除
114
+ //cellをスワイプで削除
13
115
  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
14
116
  if editingStyle == .delete {
15
117
  chatArray.remove(at: indexPath.row)
16
118
  tableView.deleteRows(at: [indexPath], with: .fade)
17
119
  }
18
120
  }
121
+
122
+
123
+ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
124
+
125
+ //メッセージの数
126
+ return chatArray.count
127
+
128
+ }
129
+
130
+ func numberOfSections(in tableView: UITableView) -> Int {
131
+
132
+ return 1
133
+ }
134
+
135
+ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
136
+
137
+ let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
138
+
139
+ cell.massageLabel.text = chatArray[indexPath.row].message
140
+
141
+
142
+ cell.userNamelabel.text = chatArray[indexPath.row].sender
143
+ cell.iconImageView.image = UIImage(named: "dogAvatarImage")
144
+
145
+ //Loginしているユーザーが自分のemailアドレスなら
146
+ if cell.userNamelabel.text == Auth.auth().currentUser?.email as! String{
147
+
148
+ //massageLabelの背景色を変更
149
+ cell.massageLabel.backgroundColor = UIColor.flatGreen()
150
+ //セルのラベルを丸くする
151
+ cell.massageLabel.layer.cornerRadius = 10
152
+ cell.massageLabel.layer.masksToBounds = true
153
+
154
+ }else{
155
+
156
+ cell.massageLabel.backgroundColor = UIColor.flatBlue()
157
+ //セルのラベルを丸くする
158
+ cell.massageLabel.layer.cornerRadius = 20
159
+ cell.massageLabel.layer.masksToBounds = true
160
+
161
+ }
162
+
163
+
164
+ return cell
165
+
166
+ }
167
+
168
+ //セルの高さを返す
169
+ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
170
+
171
+ return view.frame.size.height/10
172
+ }
173
+
174
+ @IBAction func sendAction(_ sender: Any) {
175
+
176
+ //入力が終わったから
177
+ messageTextField.endEditing(true)
178
+ messageTextField.isEnabled = false
179
+ sendButton.isEnabled = false
180
+
181
+
182
+ //送信する文字数の制限
183
+ if messageTextField.text!.count > 20{
184
+
185
+ print("20文字以上です")
186
+
187
+ return
188
+
189
+ }
190
+
191
+ //Firebase.Datebaseのhitsが作り方
192
+ let chatDB = Database.database().reference().child("chats")
193
+
194
+ //キーバリュー型で内容を送信(Dictionary型)
195
+ //送信したいものを(キー値とValue)一緒にもつ変数
196
+ let messageInfo = ["sender":Auth.auth().currentUser?.email,"message":messageTextField.text!]
197
+
198
+ //chatDBに入れる
199
+ chatDB.childByAutoId().setValue(messageInfo) { (error, result) in
200
+
201
+ if error != nil{
202
+
203
+ print(error)
204
+
205
+ }else{
206
+
207
+ print("送信完了")
208
+ self.messageTextField.isEnabled = true
209
+ self.sendButton.isEnabled = true
210
+ //TextFieldを自動的に消す作業
211
+ self.messageTextField.text = ""
212
+
213
+ }
214
+
215
+ }
216
+
217
+ }
218
+
219
+ //引っ張ってくる
220
+ func fetchChatData(){
221
+
222
+ //どこからデータを引っ張ってくるのか
223
+ let fechdataRef = Database.database().reference().child("chats")
224
+
225
+ //新しく更新があったときだけ取得したい
226
+ fechdataRef.observe(.childAdded) { (snapShot) in
227
+
228
+ //snapShotの値にmessageとsenderがある
229
+ //snapShotDataのキー値はmessageという所に保存されている
230
+ let snapShotData = snapShot.value as! AnyObject
231
+ let text = snapShotData.value(forKey: "message")
232
+ let sender = snapShotData.value(forKey: "sender")
233
+
234
+ //初期化
235
+ let message = Message()
236
+ message.message = text as! String
237
+ message.sender = sender as! String
238
+
239
+ //tableViewのchatArrayにmessageを表示できる
240
+ self.chatArray.append(message)
241
+ //データ更新
242
+ self.tableView.reloadData()
243
+
244
+ }
245
+ }
19
246
  ```