Update CALayer sublayers immediately

2020-03-07 03:36发布

问题:

I have UIView which has the following structure:

UIView
  |- layer (CALayer)
    |- depthLayer (CALayer)
    |- bodyLayer (CALayer)

For layer I set needsDisplayOnBoundsChange = true. When I change size of UIView, layer redraws immediately. But their sublayers updates with some delay (on the next draw iteration). How to sync draw of layers with sublayers depthLayer and bodyLayer?

UIView:

override func drawRect(rect: CGRect) {
    bodyLayer.frame = rect
    depthLayer.frame = CGRectOffset(rect, 0, 5)
}

回答1:

The delays you see in your CALayer's frames are cause because the Animations -> when you making a change to the CALayer's appearance It tries to animate it (and it often successes -> well this is why they called animations layers).

To disable this behavior (animations) you should call the disable transactions like this:

CATransaction.setValue(kCFBooleanTrue, forKey:kCATransactionDisableActions) //..Make Change to the frames here CATransaction.commit()

Also I don't know wether you have a real need to override the drawRect for this matter -> if you set the UIView's Frame via setFrame: method, it is better to override the setFrame: method itself and adjust the Frames of subLayers there.

Lot of Luck!