我有一个显示自定义单元格的UITableView。每个单元格包含一个滚动视图、一个图像视图和几个文本标签。这些都已经在故事板中设置好了。我在cellForRowAtIndexPath
中设置了文本标签和图像视图的各种属性。到目前为止很简单。
现在,我需要在每个单元格的滚动视图中添加数量可变的图像。目前,我更新了滚动视图的内容大小,并调用cell.contentView.addSubview
在cellForRowAtIndexPath
中添加这些图像。不幸的是,这似乎会导致内存泄漏。
如果我在表视图上上下滚动多次,它会变得非常不稳定和缓慢。我怀疑我添加到单元格的子视图没有被释放。每次调用'cellForRowAtIndexPath‘时,我都会尝试删除该单元格的所有子视图,但这似乎并不能解决问题。
我应该在哪里向单元格的滚动视图添加子视图,以便在每次重用单元格时释放它们?
下面是我的一段代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("newsFeedCell", forIndexPath: indexPath) as! NewsFeedCell
cell.layoutIfNeeded()
// Get the profile picture dimensions
self.profPicWidthHeight = getProfilePictureDimensions(cell)
// Reset all views in the friends subview
for view in cell.friends.subviews {
view.removeFromSuperview()
}
// Get all info to display in cell
cell.eventTitle.text = self.eventNames[indexPath.section]
cell.time.text = self.eventTimes[indexPath.section]
cell.entityPicture.image = self.eventImages[indexPath.section]
cell.entityName.text = self.eventSponserNames[indexPath.section]
// If this user has joined this event, add his/her image to the array
if (self.eventsUserJoined[indexPath.section]) {
self.eventUserImages[indexPath.section].append(self.meImage)
}
// Set the scroll view content size
cell.friends.contentSize = CGSizeMake(CGFloat(self.eventUserImages[indexPath.section].count + 2) * (self.profPicHorizontalOffset + self.profPicWidthHeight), cell.friends.frame.height)
// Add profile images
var i: CGFloat = 1
for profPic in self.eventUserImages[indexPath.section] {
cell.friends.addSubview(layoutProfilePicture(i, picture: profPic!, squareDimension: self.profPicWidthHeight))
i++
}
您能提供的任何帮助都是非常感谢的!
发布于 2015-08-05 21:52:53
您需要使用图像缓存来克服速度慢的问题。您的单元格每次出现在屏幕上时都会被重新绘制。如果不对图像使用inMemory缓存,将会导致速度变慢。看一下SDWebImage,并使用它来设置图像。
https://github.com/rs/SDWebImage
示例用法:
让url = NSURL(string:"http://my-images-url.com")
self.imageView.sd_setImageWithURL(url,已完成:阻止)
https://stackoverflow.com/questions/31843277
复制相似问题