CALayer - 10

前面总结了那么多CALayer的属性和知识点,我们来理一理这货究竟和UIView的区别和联系是什么,这也是面试常常有的难题!!

一番搜索,找到一个很多的解析:http://www.jianshu.com/p/079e5cf0f014 , 大牛就是大牛!

先看看大神怎么总结的:



根据文顶顶大神的教程,我们可以知道UIView作为CALayer的管理者,之所以能够显示内容,是因为CALayer层在屏幕的的绘制。而UIView继承UIResponder类,具备事件响应的能力,CALayer不具备,但是由于轻量的原因性能上更高


这里我们对比一下UIView CALayer 常见的相似的属性和方法:

1.



2.



3.



4.



5.



6.


当然还有其他非常相似的属性和方法,我们先不做细纠了


按照大牛的方法来我们继承两个UIView 和 CALayer 类,并重写UIView里面 layClass方法,跟踪到底两者关系和发生了什么事情!

.h文件:

#import <UIKit/UIKit.h>

@interface CustomerView : UIView

@end


#pragma mark - CustomerLayer.

@interface CustomerLayer : CALayer

@end


.m文件:

#import "CustomerView.h"

@implementation CustomerView


- (id)init
{
    self = [super init];
    
    if (self)
    {
        NSLog(@"CustomerCustomer init");
    }
    
    return self;
}


+ (Class)layerClass
{
    return [CustomerLayer class];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
}

- (void)setCenter:(CGPoint)center
{
    [super setCenter:center];
}

- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:backgroundColor];
}


@end



#pragma mark - CustomerLayer.

@implementation CustomerLayer

- (instancetype) init
{
    self = [super init];
    
    if (self)
    {
        NSLog(@"CustomerLayer init");
    }
    
    return self;
}

+ (instancetype) layer
{
    return [CustomerLayer layer];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
}


- (void)setPosition:(CGPoint)position
{
    [super setPosition:position];
}

- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];
}

- (void)setBackgroundColor:(CGColorRef)backgroundColor
{
    [super setBackgroundColor:backgroundColor];
}

@end
在上面每一个方法都打一个断点,可以发现,调用顺序大致如下:

init(UIView) -> layerClass(UIView) -> init(CALayer) -> setBounds(CALayer) -> setFrame(CALayer)*2 -> setPosition(CALayer) -> setBounds(CALayer) -> 开始弹出界面

当调用到layer创建了类之后我们可以看到:

可以看到UIView调用了一个私有方法,为什么是私有方法呢?因为在头文件是看不到这个方法的!根据语义上可以知道:根据Frame来创建Layer,而且这个方法的调用顺序在layerClass之后。

所以大神就猜测到UIView的setCenter 和 setBounds是不是直接根据它自身的CALayer的setPosition 和 setBounds来实现的呢?这个回想起,如果你直接setBounds和setCenter会错位,是不是一个道理?这也是iOS的不足,我们往往难以知道源码(闭源),从而难以像安卓一样知道源码实现,这个可以参考一下iOS的逆向工程


摘抄一段:

View中frame getter方法,bounds和center,UIView并没有做什么工作;它只是简单的各自调用它底层的CALayer的frame,bounds和position方法。
道理


参考:

http://www.jianshu.com/p/079e5cf0f014

http://www.cocoachina.com/industry/20131209/7498.html




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值