質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

1回答

1322閲覧

tableViewのcellのdeleteメソッドについて

Ytan

総合スコア39

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

1クリップ

投稿2020/03/22 07:02

編集2020/03/23 05:15

前提

ログイン画面にFirebaseでユーザーを管理して、新規登録とログインをして遷移してTableViewを使用したチャットアプリを作っています。

試したいこと

cellスワイプで削除するメソッドを追加したのですが、1度ログイン画面に戻ってしまうと削除したcellがまた表示され、一時的な削除となってしまいます。

ログインしなおしてもそのまま削除した状態にするにはどのような継承をすればいいですか?

Swift

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

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

chatArrayがremove(at: indexPath.row)されたあとに保存されていないのでは?

投稿2020/03/22 07:12

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Ytan

2020/03/23 03:42

多分そうだと思われます。 一度解決策を探してみます。
Ytan

2020/03/23 04:11

tableView.endUpdatesかreloadDataを使用すると思ったのですが、変わりませんでした。
退会済みユーザー

退会済みユーザー

2020/03/23 04:30

tableViewではなくて、chatArrayの保存ですよ。 読み込み、保存はどうなってますか?
Ytan

2020/03/23 04:36

chatArray.reloadDataということですか?
退会済みユーザー

退会済みユーザー

2020/03/23 04:48

データ(chatArray)の読み込みと保存はどうやってますか? tableViewと、そのメソッドは今回はかんけいないですよ。
Ytan

2020/03/23 05:01

chatArrayは他のファイルにあるMessgeクラスに var sender:String = "" var message:String = "" } として送り手(sender)とmessage(TextField)を保持しています。
退会済みユーザー

退会済みユーザー

2020/03/23 05:06

データ(chatArray)の読み込みと保存はどうやってますか?
Ytan

2020/03/23 05:16

すみません。 知識不足で質問をうまく理解できないのでコード追加しました
退会済みユーザー

退会済みユーザー

2020/03/23 05:24

データを入力したら、sendActionで保存してるでしょ、それと同じようなことを、データを削除した時か画面を、閉じた時とかにやらないと、削除した結果はfirebaseに保存されないと思わない?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問