time奔跑吧 iOS首页投稿(暂停使用,暂停投稿)

Category+链式编程打造UIView3D旋转功能

2016-11-09  本文已影响208人  民谣程序员

导语

最近很闲于是重新折腾一个做过的小功能,即让多个UIView有顺序地朝以上下左右边从里到外3D旋转,效果就像是释放了一系列压着的木板。


rotate.gif

效果

最终实现的效果如上图所示。
地址在github中:https://github.com/beautylim/Objective-C-mainViewRotate

Usage

首先看看如何使用:

topImageView.topRotate().rotateX().animationRotate(2,^(Bool flag){
    //动画完成后操作,2为2s是指定的动画完成时间
});

Analysis

Fir.  研究如何是一个UIView3D旋转;
Sec.  如何使得UIView有次序执行;
Thi.  如何使用链式编程; 
frame.oringin.x = position.x - anchorPoint.x * bounds.size.width;
frame.oringin.y = position.y - anchorPoint.y * bounds.size.height;

会变的是<code>frame</code>的<code>origin</code>,所以导致了位置的偏移,既要修改<code>layer</code>的锚点,又要使其位置不发生位移,只要在设置锚点完成后将<code>frame</code>的值改成设置锚点之前的值就OK了。

CATransform3DMakeRotation(-M_PI/4, 1, 0, 0); //控制旋转角度和以什么轴旋转,你想绕哪个轴哪个轴就为1 ,上1,下-1,左-1,右1

第一个参数控制倾斜角度,第二,三,四个参数,是形成一个旋转轴的向量,也可以简单地理解为x,y,z,想要在哪个轴旋转就在哪个位置设置为1或者-1,以一个View的上边为轴为例,应该设置为<code>1,0,0</code>,如果是下边应该是<code>-1,0,0</code>,以此类推就可以正确地设置了。

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)

只要在这里传入一个block就可以在调用页面自定义操作。
那么如何传入呢?
我的打算是在<code>Category</code>添加block属性,其实<code>Category</code>本来是不能添加属性,但是我们可以用运行时动态添加

//定义好block
typedef void (^FinishedAnima)(BOOL);
@interface UIView (Rotate)<CAAnimationDelegate>
@property (nonatomic,copy) FinishedAnima completion;//添加属性

在<code>.m</code>文件中

@implementation UIView (Rotate)
static char completionKey = 'n';//名称为属性名+Key

- (void)setCompletion:(FinishedAnima)completion{
    objc_setAssociatedObject(self, &completionKey, completion, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (FinishedAnima)completion{
    return objc_getAssociatedObject(self, &completionKey);
}

简单地绑定后就可以对<code> completion</code>赋值。

typedef UIView *(^RotateBlock)();//返回值为UIView

将可以调用的函数接口写在<code>.h</code>文件中

typedef void (^FinishedAnima)(BOOL);
typedef UIView *(^RotateAnimationBlock)(NSInteger,FinishedAnima);

- (RotateBlock)topRotate;
- (RotateBlock)bottomRotate;
- (RotateBlock)leftRotate;
- (RotateBlock)rightRotate;
- (RotateBlock)rotateX;
- (RotateBlock)rotateY;
- (RotateAnimationBlock)animationRotate;

每次使用调用这些函数返回的是自己,则又可以调用上面的函数,这样不同组合,就可以按需求自己组合成特定的调用链,试想如果不采用这种方法,根据用户的需求要写多少个<code>if else</code>或者<code>switch case</code>,所以采用链式式编程最大的好处是 组合

把变化的部分封装成一个函数,通过链式编程可以随意将这些变化组合,省去了一大堆的很长的判断。著名的应用例子有<code>Alamofire</code>(之前一直在看Swift,所以举得例子是它)。

以上就是这些内容,谢谢阅读


详情请戳Github链接
最后不要脸的希望能给个鼓励,github上给个star
上一篇下一篇

猜你喜欢

热点阅读