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

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

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

TableView(UITableView)とは、リスト形式で表示するコントロールで、ほとんどのアプリに使用されています。画面を「行」に分けて管理し、一般的には各行をタップした際に詳細画面に移動します。

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回答

2870閲覧

tableView チェックマークのずれ

退会済みユーザー

退会済みユーザー

総合スコア0

TableView

TableView(UITableView)とは、リスト形式で表示するコントロールで、ほとんどのアプリに使用されています。画面を「行」に分けて管理し、一般的には各行をタップした際に詳細画面に移動します。

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クリップ

投稿2017/10/19 07:07

編集2017/10/20 01:27

swift

1import UIKit 2 3class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource { 4 5 @IBOutlet weak var mytableView: UITableView! 6 7 var kei: [Item] = Array() 8 9 10 11 override func viewDidLoad() { 12 super.viewDidLoad() 13 14 mytableView.delegate = self 15 mytableView.dataSource = self 16 17 } 18 19 20 @IBAction func addbtr(_ sender: Any) { 21 22 23 let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert) 24 25 26 let okAction = UIAlertAction(title: "OK", style: .default, handler: { 27 (action:UIAlertAction!) -> Void in 28 29 30 if let textFields = alert.textFields { 31 32 for textField in textFields { 33 self.kei.append(Item(name: textField.text!)) 34 self.kei.append(Item(name: "cell 追加 ボタン")) 35 //(Item(name: textField.text!) 36 } 37 self.mytableView.reloadData() 38 39 } 40 }) 41 alert.addAction(okAction) 42 43 44 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) 45 alert.addAction(cancelAction) 46 47 48 alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in 49 textField.placeholder = "テキスト" 50 }) 51 52 53 alert.view.setNeedsLayout() 54 55 self.present(alert, animated: true, completion: nil) 56 57 } 58 59 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 60 return kei.count 61 } 62 63 64 func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { 65 66 switch indexPath.row { 67 case 1: 68 return indexPath; 69 default: 70 return nil; 71 } 72 } 73 74 func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { 75 return indexPath 76 } 77 78 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 79 80 let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 81 82 let item = kei[indexPath.row] 83 cell.textLabel?.text = item.name 84 cell.textLabel?.textColor = UIColor.red 85 cell.backgroundColor = UIColor.black 86 87 88 89 if cell.textLabel?.text != "cell 追加 ボタン" { 90     cell.accessoryType = item.complete ? .checkmark : .none 91 cell.textLabel?.textColor = UIColor.black 92 cell.backgroundColor = UIColor.yellow 93 94 } 95 if indexPath.row == 0 { 96 cell.textLabel?.textColor = UIColor.black 97 cell.backgroundColor = UIColor.white 98 } 99 100 return cell 101 } 102 103 func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) -> IndexPath? { 104 105 let cell = tableView.cellForRow(at: indexPath) 106 107 if cell?.textLabel?.text != "cell 追加 ボタン"{ 108 kei[indexPath.row].toggle() 109 tableView.deselectRow(at: indexPath, animated: true) 110 return nil 111 }else { 112 let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert) 113 114 let okAction = UIAlertAction(title: "OK", style: .default, handler: { 115 (action:UIAlertAction!) -> Void in 116 117 118 if let textFields = alert.textFields { 119 120 121 for textField in textFields { 122 self.kei.insert(Item(name: textField.text!), at: indexPath.row) 123 124 } 125 self.mytableView.reloadData() 126 127 } 128 }) 129 alert.addAction(okAction) 130 131 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) 132 alert.addAction(cancelAction) 133 134 alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in 135 textField.placeholder = "テキスト" 136 }) 137 138 139 alert.view.setNeedsLayout() 140 141 142 self.present(alert, animated: true, completion: nil) 143 144 return indexPath 145 } 146 147 } 148 149 150 151 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 152 if editingStyle == .delete { 153 self.kei.remove(at: indexPath.row) 154 tableView.deleteRows(at: [indexPath], with: .fade) 155 } 156 } 157 158 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { 159 160 let delete = UITableViewRowAction(style: .normal, title: "削除") {ation, index in 161 self.kei.remove(at: (indexPath.row)) 162 tableView.deleteRows(at: [indexPath], with: .fade) 163 } 164 delete.backgroundColor = .red 165 166 let edit = UITableViewRowAction(style: .normal, title: "編集") { action, index in 167 168 let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert) 169 170 171 let okAction = UIAlertAction(title: "OK", style: .default, handler: { 172 (action:UIAlertAction!) -> Void in 173 174 175 if let textFields = alert.textFields { 176 177 178 for textField in textFields { 179 self.kei[indexPath.row] = (Item(name: textField.text!)) 180 //self.kei.append(textField.text!) 181 } 182 self.mytableView.reloadData() 183 184 } 185 }) 186 alert.addAction(okAction) 187 188 189 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) 190 alert.addAction(cancelAction) 191 192 193 alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in 194 textField.placeholder = "テキスト" 195 }) 196 197 198 alert.view.setNeedsLayout() 199 200 201 self.present(alert, animated: true, completion: nil) 202 print("edit") 203 } 204 edit.backgroundColor = .orange 205 206 return [delete,edit] 207 } 208 209 /* //Method Swipe from left 210 //左から右へスワイプ 211 func tableView(_ tableView: UITableView,leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { 212 213 let removeAction = UIContextualAction(style: .normal,title: "削除",handler: { (action: UIContextualAction, view: UIView, success :(Bool) -> Void)in success(true) 214 }) 215 removeAction.image = UIImage(named: "trash") 216 removeAction.backgroundColor = .red 217 218 return UISwipeActionsConfiguration(actions: [removeAction]) 219 }*/ 220 221 222 func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 223 224 if kei.count > (indexPath.row + 1) { 225 return true 226 }else{ 227 return false 228 } 229 } 230 231 override func didReceiveMemoryWarning() { 232 super.didReceiveMemoryWarning() 233 // Dispose of any resources that can be recreated. 234 } 235 236} 237

item.swift

1struct Item { 2 var name: String 3 var complete: Bool 4 5 init(name: String) { 6 self.name = name; 7 complete = false 8 } 9 10 mutating func toggle() { 11 complete = !complete 12 } 13}

やりたいこと
cellの追加時にチェックマークがずれないようにしたいです

試したこと
https://teratail.com/questions/94578を参考にし、色々試した中で構造体を使ってみたのですがcellの追加時にやっぱりにチェックマークの位置がずれて困っています。

イメージ説明

//コード変更後
cellforRowAtにチェックマークの処理を書くとタップしてチェックマークつけたいのにタップしても反応しなくなります。

tableView.reloadRows(at: [indexPath], with: .none)

こうすることによってタップしてチェックマークをつけれるようになったのですが、なぜかcellを追加すると[cell 追加 ボタン]だけ勝手にチェックがついてしまうのですがなぜなのでしょうか?

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

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

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

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

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

guest

回答1

0

ベストアンサー

tableView(_:didSelectRowAt:)の中で、セルのチェックマークを直接触ってるからじゃないですか?

【追記】

cellforRowAtにチェックマークの処理を書くとタップしてチェックマークつけたいのにタップしても反応しなくなります

セルの状態(今回の場合はcompleteフラグ)を変更したらリロードしないと駄目ですよ。
(前回の質問の、私の回答の#3を参照)

投稿2017/10/19 07:19

編集2017/10/19 07:48
fuzzball

総合スコア16731

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

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

ykws

2017/10/19 13:20

今の状態だとスクロールして画面から一度対象のセルを隠れる状態にして、また見えるようにするとチェックがつくと思います(そのタイミングでリロードされるから) なので、セルの状態を変更したタイミングでリロードすれば意図した動作になります。
退会済みユーザー

退会済みユーザー

2017/10/19 14:01

tableView.reloadData()こちらでリロードするとタップできるようになったのですがこの場合だとチェックマークがずれるのでfuzzballさんに教えて頂いた tableView.reloadRows(at: , with: ) こちらでコードを書いてみたのですがat:とwith:の後になんて書けばいいのか分からないです。もし宜しければ教えて頂けないでしょうか? tableView.reloadRows(at: kei[indexPath.row] , with: mytableView ) 私なりにこのように書いてみたのですがエラーが出てどう書いたらいいか分からなく困っています。
fuzzball

2017/10/20 00:18

atの方は at indexPaths: [IndexPath] なので複数のindexPathをArrayで指定、 withの方は with animation: UITableViewRowAnimation なのでアニメーションの種類、となります。 今回は更新するセルが一つなので、atの方は [indexPath] 、 アニメーションは好きなものにすればいいですが、とりあえず .automatic でいいと思います。 これくらいはググって見つけて欲しいですが‥。 参考: https://developer.apple.com/documentation/uikit/uitableview/1614935-reloadrows https://developer.apple.com/documentation/uikit/uitableviewrowanimation
退会済みユーザー

退会済みユーザー

2017/10/20 01:21

すいません。昨日コメントした後にググって見つけたのですが返信するのを忘れていました。 ご迷惑をおかけしてすいませんでした。
退会済みユーザー

退会済みユーザー

2017/10/20 01:32

実行して気づいたことなのですがチェックマーク自体は@fuzzballさんと@ykwsさんのアドバイスによってチェックマークがずれなくなったのですがなぜか[cell 追加 ボタン]でcellを追加すると勝手にチェックがつくのですがこの場合、タップしたことによってチェックがついたのでしょうか?またはチェックマークがずれてついたのでしょうか?
fuzzball

2017/10/20 01:34 編集

「どこに」勝手にチェックがつくのでしょうか?
退会済みユーザー

退会済みユーザー

2017/10/20 01:43

cellを追加するためにボタンとして使っている[cell 追加 ボタン]です。スクショしたのを質問欄に載せたのでみて頂いた方分かりやすいと思います。 それとコメント後にダメごとで今、試しにcellforRowAtで[cell 追加 ボタン] のif文にelseを追加し、cell.accessoryType = .noneを加えたら[cell 追加 ボタン]にチェックがつかなくなりました。 このやり方であっているのでしょうか?
fuzzball

2017/10/20 01:52 編集

それで合っています。 ついでに書くと、if文の外にある、 cell.textLabel?.textColor = UIColor.red cell.backgroundColor = UIColor.black の二つも追加ボタン用の設定なので、今回追加したelseの中に書く方が良いと思います。
退会済みユーザー

退会済みユーザー

2017/10/20 02:03

分かりました。そうしてみます。親切にアドバイスして頂きありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問