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

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

新規登録して質問してみよう
ただいま回答率
85.50%
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

解決済

2回答

469閲覧

選択したセルの背景色を指定時間後に変更したい

NS0904

総合スコア41

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グッド

0クリップ

投稿2018/10/22 13:01

前提・実現したいこと

とあるサイトをみてtodoリスト的なアプリを作っています。

指定時間後に、アラートを使用して選択したCellの背景色を変更したいと考えております。

DispatchQueue.main.asyncAfterを使用して処理を遅らせることは理解したのですが、
下記のようにしてもテーブルが全く変更されません。

発生している問題・エラーメッセージ

アラートを使用して選択したセルの背景色が指定時間経過しても変わらない。

該当のソースコード

swift

1 2import UIKit 3 4class TodoListViewController: UITableViewController { 5 6 // アイテムの型 7 class Item { 8 var title : String 9 var done: Bool = false 10 11 init(title: String) { 12 self.title = title 13 } 14 } 15 16 // この配列に作ったアイテムを追加していく 17 var itemArray: [Item] = [] 18 19 override func viewDidLoad() { 20 21 super.viewDidLoad() 22 23 tableView.transform = CGAffineTransform(a: CGFloat(1), b: CGFloat(0), c: CGFloat(0), d: CGFloat(-1), tx: CGFloat(0), ty: CGFloat(0)) 24 25 26 navigationController?.navigationBar.prefersLargeTitles = true 27 28 let item1: Item = Item(title: "a") 29 let item2: Item = Item(title: "bbbb") 30 let item3: Item = Item(title: "cccccccc") 31 32 itemArray.append(item1) 33 itemArray.append(item2) 34 itemArray.append(item3) 35 36 37 } 38 39 40 41 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 42 43 return itemArray.count 44 45 } 46 47 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 48 49 let alert: UIAlertController = UIAlertController(title: "赤くする?青くする?削除する?", message: "", preferredStyle: UIAlertController.Style.alert) 50 51 let defaultAction: UIAlertAction = UIAlertAction(title: "削除", style: UIAlertAction.Style.default, handler:{ 52 53 (action: UIAlertAction!) -> Void in 54 self.itemArray.remove(at: indexPath.row) 55 let indexPaths = [indexPath] 56 tableView.deleteRows(at: indexPaths, with: .automatic) 57 print("削除") 58 59 }) 60 61 let cancelAction: UIAlertAction = UIAlertAction(title: "赤くする", style: UIAlertAction.Style.default, handler:{ 62 63 (action: UIAlertAction!) -> Void in 64 65 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) { 66 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 67 68 let cell = tableView.cellForRow(at:indexPath) 69 cell?.contentView.backgroundColor = UIColor.red 70 return cell! 71 } 72 self.tableView.reloadData() 73 print("赤くしました") 74 75 } 76 }) 77 78 let cancel2Action: UIAlertAction = UIAlertAction(title: "青くする", style: UIAlertAction.Style.cancel, handler:{ 79 80 (action: UIAlertAction!) -> Void in 81 print("青くしました") 82 }) 83 84 85 alert.addAction(cancelAction) 86 alert.addAction(defaultAction) 87 alert.addAction(cancel2Action) 88 89 present(alert, animated: true, completion: nil) 90 91 tableView.deselectRow(at: indexPath, animated: true) 92 93 } 94 95 96 97 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 98 99 let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath) 100 let item = itemArray[indexPath.row] 101 cell.textLabel?.text = item.title 102 cell.accessoryType = item.done ? .checkmark : .none 103 104 cell.transform = CGAffineTransform(a: CGFloat(1), b: CGFloat(0), c: CGFloat(0), d: CGFloat(-1), tx: CGFloat(0), ty: CGFloat(0)) 105 return cell 106 107 } 108 109 @IBAction func addButtonPressed(_ sender: Any) { 110 111 var textField = UITextField() 112 113 let alert = UIAlertController(title: "新しいアイテムを追加", message: "", preferredStyle: .alert) 114 115 let action = UIAlertAction(title: "リストに追加", style: .default) { (action) in 116 117 let newItem: Item = Item(title: textField.text!) 118 119 120 self.itemArray.append(newItem) 121 self.tableView.reloadData() 122 123 } 124 125 alert.addTextField { (alertTextField) in 126 alertTextField.placeholder = "新しいアイテム" 127 textField = alertTextField 128 } 129 130 alert.addAction(action) 131 present(alert, animated: true, completion: nil) 132 133 } 134 135} 136 137 138 139

試したこと

初めは、テーブルのビューを更新していなかったので、更新してみたんですが変わらずでした。

補足情報(FW/ツールのバージョンなど)

xcode10,swift4

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

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

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

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

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

guest

回答2

0

セル背景色を変更するのは、cellForRowAtの中で行わないと、
reloadDataを行った時にクリアされ(というかcellForRowAt通りの表示になり)ます。

投稿2018/10/23 03:11

t_obara

総合スコア5488

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

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

NS0904

2018/10/25 16:47

回答ありがとうございます。
guest

0

ベストアンサー

swift

1DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) { 2 let cell = tableView.cellForRow(at: indexPath) 3 cell.contentView.backgroundColor = .red 4 print("赤くしました") 5}

こうです

でもこれも間違だと後々気づくと思います
cellというのはviewを使いまわしするものなので、TodoListTableViewControllerがcellの状態をindexPathに紐づけて持っておかなければなりません
例えば100セル用意してスクロールすると、選択してないはずのcellが赤くなります

どうすればいいかと言えば、cellForRowAtIndexPathで色を付けます

状態を保持するためにはいくつかあります
・Itemに状態を付ける
・tableViewのselect状態を利用する
・cellの状態の配列をTodoListTableViewController内に持つ(いわゆるViewModel)

投稿2018/10/25 04:19

kosanai

総合スコア471

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

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

NS0904

2018/10/25 16:52

回答ありがとうございます。 できました!! すごく嬉しいのと同時に、しっかり基礎も学ばないといけないと痛感しました。 cellの再利用が問題になるということですね。 3つのアドバイスを参考にして実際にやって見ます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問