私は、ユーザーのお気に入りの投稿に応じてトグルされるボタン付きのUITableViewを持っています。テーブルビューがスクロールされるときを除いて、すべてがうまくいきます。ボタンが変わります。ここに私のコードは次のとおりです。スクロールでの値の変更UITableView
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let feed = self.feed else {
return 0
}
return feed.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if feed!.count > 9 {
if indexPath.row == feed!.count - 1 {
self.loadMorePosts()
}
}
if hasImageAtIndexPath(indexPath) {
return imageCellAtIndexPath(indexPath)
} else {
return basicCellAtIndexPath(indexPath)
}
}
func hasImageAtIndexPath(indexPath:NSIndexPath) -> Bool {
let post = self.feed?[indexPath.row]
if post?.image?.isEmpty == false {
return true
}
return false
}
func imageCellAtIndexPath(indexPath:NSIndexPath) -> PostCellImage {
let cell:PostCellImage = self.tableView.dequeueReusableCellWithIdentifier("imageCell", forIndexPath: indexPath) as! PostCellImage
if let post = self.feed?[indexPath.row] {
let likedPost = post.hasFavorited
if likedPost == true {
if let favoriteCount = post.favoriteCount {
let count = String(favoriteCount)
cell.likeButton.setTitle(count, forState: .Normal)
cell.likeButton.setImage(UIImage(named: "liked"), forState: .Normal)
cell.likeButton.setTitleColor(UIColorFromRGB("A61224"), forState: .Normal)
cell.likeButton.addTarget(self, action: "unfavoritePost:", forControlEvents: UIControlEvents.TouchUpInside)
cell.likeButton.tag = post.id!
}
} else {
if let favoriteCount = post.favoriteCount {
let count = String(favoriteCount)
cell.likeButton.setTitle(count, forState: .Normal)
cell.likeButton.addTarget(self, action: "favoritePost:", forControlEvents: UIControlEvents.TouchUpInside)
cell.likeButton.tag = post.id!
}
}
}
return cell
}
お気に入り投稿アレイ
var favoritedPosts = [Int]()
テーブルビュー
if let likedPost = post.hasFavorited {
if likedPost == true {
self.favoritedPosts.append(indexPath.row)
print(self.favoritedPosts)
}
}
if self.favoritedPosts.contains(indexPath.row) {
let count = String(post.favoriteCount)
cell.likeButton.setTitle(count, forState: .Normal)
cell.likeButton.setImage(UIImage(named: "liked"), forState: .Normal)
cell.likeButton.setTitleColor(UIColorFromRGB("A61224"), forState: .Normal)
cell.likeButton.addTarget(self, action: "unfavoritePost:", forControlEvents: UIControlEvents.TouchUpInside)
cell.likeButton.tag = post.id!
} else {
let count = String(post.favoriteCount)
cell.likeButton.setTitle(count, forState: .Normal)
cell.likeButton.addTarget(self, action: "favoritePost:", forControlEvents: UIControlEvents.TouchUpInside)
cell.likeButton.tag = post.id!
}
これは、多くの場合、誰もが1〜2回いると思う小さな落とし穴です。 'dequeReusableCells'メソッドを使用していると仮定します。スクロールすると、効率的な理由から、そのメソッドは既にテーブルにあるがウィンドウの外側にあるセルを吐き出し続けます。条件を使用していくつかのUI要素を設定する場合、セル内のすべての要素に値を指定しないと、セルの古い値が引き続き使用され、意図しない結果が返されます。私は100%あなたの問題だと確信していません。あなたの質問に 'cellForRowAtIndexPath'メソッド全体を含めることをお勧めします。 –
ちょうどコード –
を追加すると、セルの再利用に起因する問題を避けるために、ネストされた 'if'ステートメントに' else'パーツを追加するべきです。これを試してください。 –