保证视图同步 返回之前(返回调用代码之前)的退款保证,钢筋混凝土实体方法是配置CALayer
与UIView
子类的交互。
在您的UIView子类中,创建一个displayNow()
方法,该方法告诉图层“ 设置显示路线 ”,然后“ 使其如此 ”:
迅速
/// Redraws the view's contents immediately.
/// Serves the same purpose as the display method in GLKView.
public func displayNow()
{
let layer = self.layer
layer.setNeedsDisplay()
layer.displayIfNeeded()
}
目标C
/// Redraws the view's contents immediately.
/// Serves the same purpose as the display method in GLKView.
- (void)displayNow
{
CALayer *layer = self.layer;
[layer setNeedsDisplay];
[layer displayIfNeeded];
}
还要实现一种draw(_: CALayer, in: CGContext)
方法,该方法将调用您的私有/内部绘制方法(UIView
之所以有效,是因为每个都是一个CALayerDelegate
):
迅速
/// Called by our CALayer when it wants us to draw
/// (in compliance with the CALayerDelegate protocol).
override func draw(_ layer: CALayer, in context: CGContext)
{
UIGraphicsPushContext(context)
internalDraw(self.bounds)
UIGraphicsPopContext()
}
目标C
/// Called by our CALayer when it wants us to draw
/// (in compliance with the CALayerDelegate protocol).
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
UIGraphicsPushContext(context);
[self internalDrawWithRect:self.bounds];
UIGraphicsPopContext();
}
并创建您的自定义internalDraw(_: CGRect)
方法以及故障保护draw(_: CGRect)
:
迅速
/// Internal drawing method; naming's up to you.
func internalDraw(_ rect: CGRect)
{
// @FILLIN: Custom drawing code goes here.
// (Use `UIGraphicsGetCurrentContext()` where necessary.)
}
/// For compatibility, if something besides our display method asks for draw.
override func draw(_ rect: CGRect) {
internalDraw(rect)
}
目标C
/// Internal drawing method; naming's up to you.
- (void)internalDrawWithRect:(CGRect)rect
{
// @FILLIN: Custom drawing code goes here.
// (Use `UIGraphicsGetCurrentContext()` where necessary.)
}
/// For compatibility, if something besides our display method asks for draw.
- (void)drawRect:(CGRect)rect {
[self internalDrawWithRect:rect];
}
现在,myView.displayNow()
只要真正需要绘制(例如从CADisplayLink
回调)时就调用。我们的displayNow()
方法将告知CALayer
to displayIfNeeded()
,后者将同步回调到我们中draw(_:,in:)
并进行绘制internalDraw(_:)
,并在继续之前用绘制到上下文中的内容更新视觉效果。
这种方法类似于@RobNapier的上述方法,但是具有调用displayIfNeeded()
之外的优势setNeedsDisplay()
,这使得它可以同步。
这是可能的,因为CALayer
s比UIView
s 具有更多的绘图功能-图层比视图更底层,并且是为在布局内进行高度可配置的绘图而明确设计的,并且(像Cocoa中的许多事物一样)被设计为灵活使用(作为父类,或作为委托人,或作为与其他绘图系统的桥梁,或仅靠它们自己)。CALayerDelegate
协议的正确使用使所有这些成为可能。
有关CALayer
s可配置性的更多信息,请参见《核心动画编程指南》的“ 设置图层对象”部分。