1.什么是类目(类别)
类别( category )是 Objective-C 语言的新特性,为现有的类添加新方法的方式。比如系统的类,我们看不到他的.m文件,所以没有办法用直接添加方法的方式去实现,用类目就可以实现在没有类的源代码的条件下为类增加新的方法。
通过类目加入的方法会成为原始类的一部分。例如:通过类目想NSString增加方法,编译器会把这些方法加到NSString的定义里;类目里定义的方法可以干任何原始类中方法能干的事,在运行时他们是平等对待的;类目里定义的方法也会被原始类的子类所继承,就跟原始类的其他方法一样。
2.类目的局限性
a、无法添加新的实例变量。
b、若在类目中覆盖现有类的原有方法。这样会引起super消息的断裂,因为类目总的方法具有更高的优先级,因此,一般不要覆盖现有类中的方法
3.类目的声明结构
@interface 要加类目的类名*****例如UIView(类目名*****例如animation)
//声明类目添加的方法
@end
二、类目的添加方法功能
我们下面举一个为系统的类UIView通过类目添加方法的例子
1.首先建立一个项目,添加一个主页ViewController类,然后为UIView类添加一个类目类UIView+Category
过程:创建新工程 ->comman+n新建如下图
之后就会生成UIView+Category的.h和.m文件,之后就可以为UIView类添加方法了,下面直接上代码来说明
在UIView+Category.h中
@interfaceUIView (category)
- (void)startShakeAnimation;//摇动动画
- (void)stopShakeAnimation;
- (void)startRotateAnimation;//360°旋转动画
- (void)stopRotateAnimation;
///截图
- (UIImage*)screenshot;
@property(nonatomic)floattop;
@property(nonatomic)floatbottom;
@property(nonatomic)floatleft;
@property(nonatomic)floatright;
@end
在NSString+Category.m中
@implementationUIView (category)
/*截图*/
- (UIImage*)screenshot
{
UIGraphicsBeginImageContextWithOptions(self.frame.size,NO,2.0);
[self.layerrenderInContext:UIGraphicsGetCurrentContext()];
UIImage*image =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnimage;
}
#pragma mark - Animation
- (void)startShakeAnimation
{
CGFloatrotation =0.05;
CABasicAnimation*shake = [CABasicAnimationanimationWithKeyPath:@"transform"];
shake.duration=0.2;
shake.autoreverses=YES;
shake.repeatCount=MAXFLOAT;
shake.removedOnCompletion=NO;
shake.fromValue= [NSValuevalueWithCATransform3D:CATransform3DRotate(self.layer.transform, -rotation,0.0,0.0,1.0)];
shake.toValue= [NSValuevalueWithCATransform3D:CATransform3DRotate(self.layer.transform,rotation,0.0,0.0,1.0)];
[self.layeraddAnimation:shakeforKey:@"shakeAnimation"];
}
- (void)stopShakeAnimation
{
[self.layerremoveAnimationForKey:@"shakeAnimation"];
}
- (void)startRotateAnimation
{
CABasicAnimation*shake = [CABasicAnimationanimationWithKeyPath:@"transform"];
shake.duration=0.5;
shake.autoreverses=NO;
shake.repeatCount=MAXFLOAT;
shake.removedOnCompletion=NO;
shake.fromValue= [NSValuevalueWithCATransform3D:CATransform3DRotate(self.layer.transform,M_PI,0.0,0.0,1.0)];
shake.toValue= [NSValuevalueWithCATransform3D:CATransform3DRotate(self.layer.transform,0.0,0.0,0.0,1.0)];
[self.layeraddAnimation:shakeforKey:@"rotateAnimation"];
}
- (void)stopRotateAnimation
{
[self.layerremoveAnimationForKey:@"rotateAnimation"];
}
-(float)top
{
returnself.frame.origin.x;
}
-(float)bottom
{
returnself.top+self.frame.size.height;
}
-(float)left
{
returnself.frame.origin.x;
}
-(float)right
{
returnself.left+self.frame.size.width;
}
@end
在ViewController中导入UIView+Category.h后可直接通过UIView调用- (void)startRotateAnimation方法
原文地址:https://github.com/github0625/Category/tree/master/CategoryTest/CategoryTest