加载图像时,UITableView中的滚动非常不稳定

时间:2015-02-01 23:35:37

标签: ios xcode image uitableview swift

我正在创建一个应用程序,在一个结构中保存大约26个图像,然后我将这些图像加载到表视图中,并且只要新图像进入模拟器的视图,就会有一些滞后。处理在Table View中加载图像肯定是一个问题。

我想我需要添加异步,但我不知道该怎么做。如果有人可以指导我做正确的方向来实现平滑滚动,那就太棒了!

我希望我可以发布照片,但我在StackOverFlow.com上没有足够的声誉。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    var question : Question

    question = Questions[indexPath.row]

    var titleLabel = cell.contentView.viewWithTag(1) as UILabel

    titleLabel.text = question.name

    var backgroundImage = cell.contentView.viewWithTag(5) as UIImageView

    backgroundImage.image = UIImage(named: question.pic)

    var frame : CGRect = CGRectMake(0, backgroundImage.frame.size.height - 200, backgroundImage.frame.size.width, backgroundImage.frame.size.height - 200)

    cell.layer.shouldRasterize = true
    cell.layer.rasterizationScale = UIScreen.mainScreen().scale

    return cell

}

2 个答案:

答案 0 :(得分:1)

它与图像的大小有关。对tableView单元格使用较小的缩略图。将图像转换为较小的图像。

CGSize destinationSize = CGSizeMake(160, 160);
UIGraphicsBeginImageContext(destinationSize);
[originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

答案 1 :(得分:0)

克罗伊茨贝格的回答解决了我的问题,因为即使实施了GCD和main_queue,我的表现仍然不稳定。由于我无法在评论中添加太多代码,因此我扩展了他的答案,因此宽度/高度可能会更加动态。

if (image.size.width > MAX_THUMBNAIL_RESOLUTION || image.size.height > MAX_THUMBNAIL_RESOLUTION) {
    int width;
    int height;
    CGFloat ratio = image.size.width/image.size.height;

    if (ratio > 1) {
        width = MAX_THUMBNAIL_RESOLUTION;
        height = width / ratio;
    }
    else {
        height = MAX_THUMBNAIL_RESOLUTION;
        width = height * ratio;
    }

    CGSize destinationSize = CGSizeMake(width, height);
    UIGraphicsBeginImageContext(destinationSize);
    [image drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

您可以将常量MAX_THUMBNAIL_RESOLUTION设为您认为合理的任何内容。或者,您可以计算屏幕密度并使用乘数。