【问题标题】:rasterize cells of tableview only when scrolling in swift仅在快速滚动时栅格化表格视图的单元格
【发布时间】:2015-03-18 00:51:19
【问题描述】:

我有一个具有漂亮图形的表格视图(圆角、使用 clearcolor() 的透明单元格等)。我也在使用 maskToBounds,因此使滚动平滑的唯一方法是设置 layer.shouldRasterize = true。 这工作正常,但是当我删除一个单元格或拖动一个单元格以移动和重新排列时,我看到“伪影”主要是单元格在我的表格视图中瞬间失去透明度,因为单元格正在从光栅化更新它的内容

我只想在滚动时栅格化 tableviewcells,所以我尝试了各种方法,包括一种非常肮脏的方法,一旦 tableView.contentOffset.y 发生变化,我就会栅格化为 true,然后将其延迟一秒钟模拟滚动所需的时间并将其设置回 false。

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

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

        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell
  cell.textLabel?.text = cellitemcontent[indexPath.row]
  //here I have all the custom cell design...

   var currentOffset = tableView.contentOffset.y
    cell.layer.shouldRasterize = true
    if currentOffset > 0
    { cell.layer.shouldRasterize = true}
    else{
        delay(1.5){
        cell.layer.shouldRasterize = false

        }
    }
   return cell
}

有人可以指出一种更清洁的方法吗? 谢谢。

【问题讨论】:

    标签: uitableview swift


    【解决方案1】:

    我会拥有这些属性

    weak var tableView : UITableView!
    var isScrolling = false
    

    由于 UITableViewDelegate 协议扩展了 UIScrollViewDelegate,我将实现

    func visibleCellsShouldRasterize(aBool:Bool){
        for cell in tableView.visibleCells() as [UITableViewCell]{
            cell.layer.shouldRasterize = aBool;
        }
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        isScrolling = false
        self.visibleCellsShouldRasterize(isScrolling)
    }
    
    func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        if velocity == CGPointZero{
            isScrolling = false
            self.visibleCellsShouldRasterize(isScrolling)
        }
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        isScrolling = true
        self.visibleCellsShouldRasterize(isScrolling)
    
    }
    

    为可见单元格和进入屏幕的单元格切换 shouldRasterize,我将实现

    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.layer.shouldRasterize = isScrolling
    }
    

    【讨论】: