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

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

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

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

Swift

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

Q&A

解決済

1回答

3017閲覧

UITableViewで、下と上にテーブルを引っ張って更新するときのエラー

arsro

総合スコア24

iOS

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

Swift

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

0グッド

0クリップ

投稿2015/12/30 08:25

UITableViewを使って、データのリフレッシュ・ページングをしたいと考えているのですが、
下に引っ張ってリフレッシュするときに
大きく下に引っぱってしまうと、エラーが起きていまいます。

swift

1fatal error: Array index out of range

はじめは、リフレッシュを行った時に同時にページング処理も行っているためだと思うのですが、現状エラーを解決することができません。

swift

1import Foundation 2import UIKit 3import Alamofire 4import SwiftyJSON 5 6class RequestViewController:UIViewController,UITableViewDataSource,UITableViewDelegate{ 7 8 @IBOutlet weak var table: UITableView! 9 10 11 private var userNameArray: [String]! = [] 12 private var userImgArray: [String]! = [] 13 private var userIDArray: [Int]! = [] 14 private var userIndexArray: [Int]! = [] 15 private var userImage: String! 16 private var dataCount:Int! = 0 17 private var loadingCounter:Int! = 0 18 private var beforeUserIDArray:Int! = 0 19 20 21 private let loadNow: UIActivityIndicatorView! = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50)) 22 23 var refreshControl:UIRefreshControl! = UIRefreshControl() 24 25 override func viewDidLoad() { 26 super.viewDidLoad() 27 self.table.backgroundColor = UIColor(white: 0.95, alpha: 1) 28 self.getRequest() 29 30 self.refreshControl = UIRefreshControl() 31 //self.refreshControl.attributedTitle = NSAttributedString(string: "引っ張って更新") 32 self.refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) 33 self.table.addSubview(refreshControl) 34 35 //// スクロールする毎にロードする際のインジケーター表示 36 self.loadNow.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray 37 } 38 39 func refresh() 40 { 41 print("refresh!!!") 42 //取得した配列を開放 43 self.userNameArray.removeAll() 44 self.userImgArray.removeAll() 45 self.userIDArray.removeAll() 46 self.userIndexArray.removeAll() 47 48 //loading countの初期化 49 self.loadingCounter = 0 50 //セルのカウントを初期化 51 self.dataCount = 0 52 self.getRequest() 53 } 54 55 func scrollViewDidEndDecelerating(scrollView: UIScrollView) { 56 print("SCROLL") 57 if self.table.contentOffset.y >= self.table.contentSize.height - self.table.bounds.size.height { 58 print("self.table.contentOffset.y = \(self.table.contentOffset.y)") 59 print("self.table.contentSize.height =\(self.table.contentSize.height)") 60 print("self.table.bounds.size.height = \(self.table.bounds.size.height)") 61 62 if self.loadNow.isAnimating() == false { 63 print("self.loadNow.isAnimating() == false ") 64 print(self.loadingCounter) 65 if self.loadingCounter != 0{ 66 print("scrollViewDidEndDecelerating ") 67 self.getRequest() 68 } 69 } 70 } 71 } 72 73 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 74 // tableCell の ID で UITableViewCell のインスタンスを生成 75 let cell = self.table.dequeueReusableCellWithIdentifier("requestTableCell", forIndexPath: indexPath) 76 77 //選択しても色がつかない状態にする 78 cell.selectionStyle = UITableViewCellSelectionStyle.None 79 80 // Tag番号1で UILabel インスタンスの生成 81 let content1 = self.table.viewWithTag(-1) as! UILabel 82 let content2 = self.table.viewWithTag(-5) as! UILabel 83 84 if cell.viewWithTag(-3) != nil && cell.viewWithTag(-4) != nil{ 85 var allowButton: UIButton = UIButton() 86 allowButton = cell.viewWithTag(-3) as! UIButton 87 allowButton.addTarget(self, action: "touchAllowBtn:",forControlEvents: .TouchUpInside) 88 89 var dontAllowButton: UIButton = UIButton() 90 dontAllowButton = cell.viewWithTag(-4) as! UIButton 91 dontAllowButton.addTarget(self, action: "touchDontAllowBtn:", forControlEvents: .TouchUpInside) 92 93 content1.text = nil 94 content1.text = "\(self.userNameArray[indexPath.row])" 95 96 content2.text = nil 97 content2.text = "\(self.userIDArray[indexPath.row])" 98 99 self.userImage = self.userImgArray[indexPath.row] 100 self.setUserImg(cell, path: indexPath.row) 101 } 102 103 104 return cell 105 } 106 107 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 108 if self.dataCount != 0 { 109 return self.dataCount 110 } 111 return 0 112 } 113 114 override func didReceiveMemoryWarning() { 115 super.didReceiveMemoryWarning() 116 } 117 118 119 120 //通知内容読み込み用関数 121 func getRequest(){ 122 print("loading count = \(self.loadingCounter)") 123 print("self.refreshControl.refreshing = \(self.refreshControl.refreshing)") 124 // ローディングアイコン処理 125 self.table.tableFooterView = self.loadNow 126 if self.refreshControl.refreshing == false{ 127 self.loadNow.hidden = false 128 self.loadNow.startAnimating() 129 } 130 Alamofire.request(.GET, Const().URL_API + "/activities/showRequest", parameters: ["my_id": 1 , "loading" :self.loadingCounter]) 131 .response { request, response, data, error in 132 if error == nil { 133 let json = JSON(data: data!) 134 //print("JSON = \(json)") 135 self.dataCount = json["request_data"].count + self.dataCount 136 for var i = 0; i < json["request_data"].count; i++ { 137 if(json["request_data"][i]["user_name"] != nil){ 138 self.userNameArray.append(json["request_data"][i]["user_name"].string!) 139 }else{ 140 self.userNameArray.append("") 141 } 142 //ユーザーIDを取得するコードを挿入 143 if(json["request_data"][i]["user_id"] != nil){ 144 self.userIDArray.append(json["request_data"][i]["user_id"].int!) 145 }else{ 146 self.userIDArray.append(0) 147 } 148 149 if(json["request_data"][i]["user_img_url"] != nil){ 150 self.userImgArray.append(json["request_data"][i]["user_img_url"].string!) 151 }else{ 152 self.userImgArray.append("no_data") 153 } 154 155 if(json["request_data"][i]["relation_index"] != nil){ 156 self.userIndexArray.append(json["request_data"][i]["relation_index"].int!) 157 }else{ 158 self.userIndexArray.append(999) 159 } 160 } 161 self.table.reloadData() 162 //更新が終わったのでグリグリを削除 163 if self.loadNow.isAnimating() == true{ 164 self.loadNow.stopAnimating() 165 } 166 if self.refreshControl.refreshing == true{ 167 self.refreshControl.endRefreshing() 168 } 169 self.loadingCounter = self.loadingCounter + 1 170 } 171 else { 172 print("error!") 173 } 174 } 175 } 176 177 //画像処理 178 func setUserImg(cell: UITableViewCell, path: Int){ 179 let userImage: UIImageView = cell.viewWithTag(-2) as! UIImageView 180 userImage.backgroundColor = UIColor.lightGrayColor() 181 userImage.layer.cornerRadius = 27.5 182 183 userImage.image = nil 184 185 if self.userImage != "no_data" { 186 Alamofire.request(.GET, self.userImage) 187 .response { request, response, data, error in 188 if error == nil { 189 dispatch_async(dispatch_get_main_queue()) { () in 190 userImage.image = UIImage(data: data!) 191 //colonyImage.addGestureRecognizer(colonyImageTapRecognizer) 192 } 193 } 194 else { 195 print("error!") 196 } 197 } 198 userImage.layer.masksToBounds = true 199 } 200 else { 201 userImage.image = nil 202 } 203 } 204 205 func touchAllowBtn(sender: UIButton) { 206 let btn: UIButton! = sender 207 let cell: UITableViewCell = btn.superview?.superview as! UITableViewCell 208 let index:Int = (self.table.indexPathForCell(cell)?.row)! 209 210 if sender.currentTitle == "allow"{ 211 print("userIndex = \(self.userIndexArray[index])") 212 print("userID = \(self.userIDArray[index])") 213 } 214 } 215 216 func touchDontAllowBtn(sender: UIButton) { 217 218 let btn: UIButton! = sender 219 let cell: UITableViewCell = btn.superview?.superview as! UITableViewCell 220 let index:Int! = (self.table.indexPathForCell(cell)?.row)! 221 222 print("ID = \(index)") 223 if sender.currentTitle == "dont"{ 224 print("userID = \(self.userIDArray[index])") 225 226 self.deleteCell(self.userIDArray[index]) 227 } 228 } 229}

なにかありましたら、随時補足させていただきますのでよろしくお願い致します。

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

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

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

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

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

guest

回答1

0

ベストアンサー

上記エラーは、配列に対して存在しないindexへのアクセスがあったときに起きるエラーのようですね。

TableViewのセル数はdataCountの値を使用していますが、
userNameArray,userImgArray,userIDArray,userIndexArray
それぞれの配列数と同期がとれていないのではないのでしょうか?

それぞれのパラメータごとに配列を用意するのではなく、

Swift

1 2 3 4class ResponseData: NSObject { 5 let userImgArray: String 6 let userID: Int 7 let userIndex: Int 8}

な感じでモデルクラスを作成して、このモデルを配列で管理すれば、こういった問題は発生しないのかなと思います。

投稿2016/01/08 08:04

masashimizuno

総合スコア42

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問