How can I speed up a UITableView?

前端 未结 9 1913
广开言路
广开言路 2020-12-22 23:17

I have a UITableView with about 400 cells in 200 sections and it\'s a little sluggish in responding to user interaction (scrolling, selecting cells.) I\'ve made sure the met

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-23 00:02

    This is a little off-topic here (because you have only one background image for all cells):

    My app displays different images in each cell. After adding about 5 cells to UITableView - table is slowed down drastically. It takes about 1-2 seconds to process all images each time i open view controller.

    if let image = UIImage(contentsOfFile: photoFile){
        // just set it and let system fit it
        //cell.imageView!.image = image
    
        // 1 - Calculate sized
        let DEFAULT_THUMBNAIL_WIDTH: CGFloat  = (cellHeight / 4) * 5;
        let DEFAULT_THUMBNAIL_HEIGHT: CGFloat = cellHeight;
    
        let aspectRatio: CGFloat = image.size.width / image.size.height
        var willBeHeight = DEFAULT_THUMBNAIL_HEIGHT
        var willBeWidth  = DEFAULT_THUMBNAIL_HEIGHT * aspectRatio
    
        if(willBeWidth > DEFAULT_THUMBNAIL_WIDTH){
            willBeWidth = DEFAULT_THUMBNAIL_WIDTH
            willBeHeight = willBeWidth / aspectRatio
        }
    
        let eps:CGFloat = 0.000001
        assert((willBeHeight - eps) <= DEFAULT_THUMBNAIL_HEIGHT);
        assert((willBeWidth - eps) <= DEFAULT_THUMBNAIL_WIDTH);
    
        // 2 - Create context
        var size:CGSize = CGSize(
            width: DEFAULT_THUMBNAIL_WIDTH,
            height: DEFAULT_THUMBNAIL_HEIGHT)
        UIGraphicsBeginImageContext(size)
    
        // one-to-one rect
        //var imageRect: CGRect = CGRectMake(0.0, 0.0, size.width, size.height)
        var imageRect: CGRect = CGRectMake(0.0, 0.0, willBeWidth, willBeHeight)
    
        // 3 - Draw image
        image.drawInRect(imageRect)
        var imageResult: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        cell.imageView!.image = imageResult
    
        UIGraphicsEndImageContext()
    }else{
        DDLogError("Can not draw photo: \(photoFile)")
    }
    

    So i've ended up with generating small THUMBNAILS for all my images.

提交回复
热议问题