簡體   English   中英

加載圖像時,UITableView中的滾動非常不穩定

[英]Scrolling is very choppy in UITableView when loading images

我正在創建一個應用程序,該應用程序在結構中容納約26張圖像,然后將這些圖像加載到表格視圖中,並且每當新圖像進入模擬器的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

}

它與圖像的大小有關。 為tableView單元格使用較小的縮略圖。 為其轉換較小的圖像。

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

克羅伊茨貝格(Kreuzberg)的答案解決了我的問題,因為即使使用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設置為您認為合理的值。 或者,您可以計算屏幕密度並使用乘數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM