【问题标题】:Swift Variable Number of Subviews in Custom UITableViewCell自定义 UITableViewCell 中的 Swift 可变子视图数
【发布时间】:2015-10-28 20:45:21
【问题描述】:

我有一个显示自定义单元格的 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++
    }

非常感谢您提供的任何帮助!

【问题讨论】:

  • self.eventUserImages[indexPath.section].append(self.meImage) 无限增长数组。
  • @rintaro 谢谢!删除这段代码解决了问题!

标签: ios swift uitableview memory


【解决方案1】:

您需要使用图像缓存来克服缓慢的问题。您的单元格每次出现在屏幕上时都会重新绘制。如果您不对图像使用 inMemory 缓存,则会导致速度变慢。查看 SDWebImage 并将其用于设置图像。

https://github.com/rs/SDWebImage

示例使用:

让 url = NSURL(string: "http://my-images-url.com")

self.imageView.sd_setImageWithURL(url, completed: block)

【讨论】:

  • 我不明白。如果每个单元格中有固定数量的图像,并且我将它们布置在情节提要中,则表格不会出现故障。即使我在每个单元格中有 20 张图像。只有当我在cellForRowAtIndexPath 中调用cell.contentView.addSubview 时,表才会变慢。此外,我已经在 viewDidLoad 中预加载了所有图像,并且一开始一切正常
  • 您是远程获取图像还是将它们存储在本地?
  • 我远程获取图像,然后将它们全部存储在本地。即使我在整个表格视图中只有一个图像并且我滚动了足够多的次数,同样的问题仍然存在
  • 如果每次绘制单元格时远程获取它们,没有缓存,它会很慢。因此,正如我所建议的,为此请研究一些快速友好的图像缓存库。
  • 我只在viewDidLoad 中获取图像一次。每次绘制单元格时,我都会访问必要图像的本地副本。不过,这个查找似乎不是问题所在。我第一次上下滚动表格视图大约 30 次,效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
相关资源
最近更新 更多