一群程序猿的秘密基地iOS进阶指南iOS开发

利用Category创建类的方法,快速修改frame,提高编程效

2016-07-19  本文已影响203人  iiKris

Category是Objective-C 2.0之后添加的语言特性,Category的主要作用是为已经存在的类添加方法。通过Category可以把类的实现分开在几个不同的文件里面,这样做一是可以减少单个文件的体积,二是可以把不同的功能组织到不同的Category里面,三是可以按需加载想要的Category 等等。

一般我们修改某一个frame属性的时候都需要比较繁琐的代码书写,这样既费时费力,并且工程量较大的时候也会减弱代码的可读性,因此我们可以通过建立UIView的类别Category来实现修改frame属性的简单操作。

1.创建类别


创建Objective-C File文件 File的名字根据自己的习惯设定,最好是容易识别

(1)UIView+SHK.h


.h文件定义的属性可以根据自己需求添加

#import<UIKit/UIkit.h>

@interface UIView (SHK)

@property(nonatomic,assign) CGFloat x;

@property(nonatomic,assign) CGFloat y;

@property(nonatomic,assign) CGFloat centerX;

@property(nonatomic,assign) CGFloat centerY;

@property(nonatomic,assign) CGFloat width;

@property(nonatomic,assign) CGFloat height;

@property(nonatomic,assign) CGSize size;

@property(nonatomic,assign) CGPoint origin;

@end

(2)UIView+SHK.m

.m文件实现各个属性的setter方法和getter方法

#import"UIView+SHK.h"

@implementation UIView (SHK)

-(void)setX:(CGFloat)x{

CGRect frame=self.frame;

frame.origin.x=x;

self.frame=frame;

}

-(CGFloat)x{

returnself.frame.origin.x;

}

-(void)setY:(CGFloat)y{

CGRect frame=self.frame;

frame.origin.y=y;

self.frame=frame;

}

-(CGFloat)y{

returnself.frame.origin.y;

}

-(void)setCenterX:(CGFloat)centerX{

CGPoint center=self.center;

center.x=centerX;

self.center=center;

}

-(CGFloat)centerX{

returnself.center.x;

}

-(void)setCenterY:(CGFloat)centerY{

CGPoint center=self.center;

center.y=centerY;

self.center=center;

}

-(CGFloat)centerY{

returnself.center.y;

}

-(void)setWidth:(CGFloat)width{

CGRect frame=self.frame;

frame.size.width=width;

self.frame=frame;

}

-(CGFloat)width{

returnself.frame.size.width;

}

-(void)setHeight:(CGFloat)height{

CGRect frame=self.frame;

frame.size.height=height;

self.frame=frame;

}

-(CGFloat)height{

returnself.frame.size.height;

}

-(void)setSize:(CGSize)size{

CGRect frame=self.frame;

frame.size=size;

self.frame=frame;

}

-(CGSize)size{

returnself.frame.size;

}

-(void)setOrigin:(CGPoint)origin{

CGRect frame=self.frame;

frame.origin=origin;

self.frame=frame;

}

-(CGPoint)origin{

returnself.frame.origin;

}

@end

(3)简单的使用示例

导入头文件进行使用,frame的属性修改变得异常简单

#import"ViewController.h"

#import"UIView+SHK.h"  

@interface ViewController()

@end

@implementation ViewController

- (void)viewDidLoad {

[superviewDidLoad];

self.view.backgroundColor=[UIColorwhiteColor];

UIButton*btn1=[[UIButtonalloc]init];

btn1.backgroundColor=[UIColorredColor];

btn1.width=100;

btn1.height=100;

btn1.centerX=self.view.width*0.5;

btn1.centerY=self.view.height*0.5;

[self.viewaddSubview:btn1];

}

@end

小结

以上方法是针对近期自学新浪微博项目的一点小小总结,行笔简陋,如有错误,望指正。

上一篇下一篇

猜你喜欢

热点阅读