自定义UITableViewCell中的Swift可变数量的子视图

时间:2015-08-05 21:36:47

标签: ios swift uitableview memory

我有一个显示自定义单元格的UITableView。每个单元格包含滚动视图,图像视图和几个文本标签。这一切都已在故事板中设置。我在cellForRowAtIndexPath中设置了文本标签和图像视图的各种属性。直截了当。

现在,我需要在每个单元格的scrollview中添加可变数量的图像。目前,我更新了滚动视图的内容大小,并调用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++
    }

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

1 个答案:

答案 0 :(得分:1)

您需要使用图像缓存来克服缓慢。每次它们出现在屏幕上时,都会重绘您的单元格。如果不对图像使用inMemory缓存,则会导致缓慢。看看SDWebImage并用它来设置图像。

https://github.com/rs/SDWebImage

使用示例:

让url = NSURL(字符串:“http://my-images-url.com”)

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

相关问题