私はUITableViewを持っており、(UIImageViewを使って)各カスタムセルに異なる画像を表示する必要があります。それらを適切に表示するには、各画像のアスペクト比を計算し、UIImageViewのフレームを調整する必要があります。しかし問題がある。アプリケーションを実行すると、すべてのセルのアスペクト比が正しく表示されません。その後、私はテーブルの底に滑り始め、何度かトップに戻ってきます。そして、私は正しいアスペクト比を見るたびに、いくつかの細胞については、他の人には間違っています。システムがプロトタイプのセルを再利用しているからですか?ここでUITableViewCell、画像とアスペクト比
はtableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
のコードです:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("EntryCell", forIndexPath: indexPath) as? PodCell
let podcast = podList[indexPath.row]
let title = podcast.title
// cell.titleLa?.text = title
cell?.titleLabel.lineBreakMode = .ByWordWrapping
cell?.titleLabel.numberOfLines = 0
cell?.titleLabel.text = title
var image = UIImage()
if (imageCache[podcast.imageURL!] != nil) {
image = imageCache[podcast.imageURL!]!
cell?.imgView.image = image
}else{
let imgURL = NSURL(string: podcast.imageURL!)
let request = NSURLRequest(URL: imgURL!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error:NSError?) in
if error == nil {
if data != nil {
image = UIImage(data: data!)!
}
dispatch_async(dispatch_get_main_queue(), {
self.imageCache[podcast.imageURL!] = image
cell?.imgView.image = image
})
}else {
print(error)
}
}
task.resume()
}
let aspectRatio = image.size.width/image.size.height
cell?.imgView.frame = CGRectMake((cell?.imgView.frame.origin.x)!, (cell?.imgView.frame.origin.y)!, (cell?.imgView.frame.width)!, (cell?.imgView.frame.width)!/aspectRatio)
return cell!
}
定数値は幅です。私はセルの幅と同じ幅にする必要があります – ttrs