iOS-Objective-CiOS开发iOS Developer

iOS中分类(category)的使用

2017-07-31  本文已影响96人  追沐

分类(category)

使用(以UIView为例)

1、创建一个分类

(1)Cmd+N,iOS-->Objective-C File,Next;
(2)File Type选择category,class选择需要的类,分类名,Next。

2、分类文件

这是给UIView的frame写的一个分类

#import <UIKit/UIKit.h>

@interface UIView (Frame)

//添加的成员变量
@property CGFloat origin_x;
@property CGFloat origin_y;

@property CGFloat width;
@property CGFloat height;

//扩展的方法
/**
 *  @author MX, 16-05-29 15:05:22
 *
 *  位移(根据center移动)
 *
 *  @param point
 */
- (void)moveTo:(CGPoint) point;
/**
 *  @author MX, 16-05-29 15:05:27
 *
 *  指定比率放大或者缩小
 *
 *  @param scale    指定的比率
 */
- (void)scaleBy:(CGFloat) scale;

@end
#import "UIView+Frame.h"

@implementation UIView (Frame)

@dynamic origin_x;
@dynamic origin_y;
@dynamic width;
@dynamic height;

//实现set、get方法
- (CGFloat)origin_x
{
    return self.frame.origin.x;
}
- (CGFloat)origin_y
{
    return self.frame.origin.y;
}
- (CGFloat)width
{
    return self.frame.size.width;
}
- (CGFloat)height
{
    return self.frame.size.height;
}
- (CGFloat)toLeftMargin
{
    return self.frame.origin.x+self.frame.size.width;
}
- (CGFloat)toTopMargin
{
    return self.frame.origin.y+self.frame.size.height;
}


- (void)setWidth:(CGFloat)width
{   
    if (width != self.frame.size.width) {
        CGRect newframe = self.frame;
        newframe.size.width = width;
        self.frame = newframe;
    }
}
- (void)setHeight:(CGFloat)height
{  
    if (height != self.frame.size.height)
    {
        CGRect newframe = self.frame;
        newframe.size.height = height;
        self.frame = newframe;
    }
}
- (void)setOrigin_x:(CGFloat)origin_x
{  
    if (origin_x != self.frame.origin.x)
    {
        CGRect newframe = self.frame;
        newframe.origin.x = origin_x;
        self.frame = newframe;
    }
}
- (void)setOrigin_y:(CGFloat)origin_y
{   
    if (origin_y != self.frame.origin.y)
    {
        CGRect newframe = self.frame;
        newframe.origin.y = origin_y;
        self.frame = newframe;
    }
}

#pragma mark 扩展的方法
- (void)moveTo:(CGPoint) point
{
    if ((self.center.x != point.x) || (self.center.y != point.y))
    {
        [UIView animateWithDuration:.3 animations:^{
            CGPoint newCenter = self.center;
            newCenter.x += point.x;
            newCenter.y += point.y;
            self.center = newCenter;
        }];
    }
}
- (void)scaleBy:(CGFloat) scale
{
    if (scale >0 && scale != 1)
    {
        [UIView animateWithDuration:.3 animations:^{
            CGRect newframe = self.frame;
            newframe.size.width *= scale;
            newframe.size.height *= scale;
            self.frame = newframe;
        }];
    }
}

@end

上面对于UIView写的分类,添加了成员变量,而且扩展了UIView类的方法。

最后

参考文档:http://www.cocoachina.com/ios/20161018/17784.html
这里总结了一些经常用的分类https://github.com/Mexiang/category,都是简单经常用的方法,会持续总结更新github。

上一篇 下一篇

猜你喜欢

热点阅读