Category是Objective-C 2.0之后添加的語言特性芋绸,Category的主要作用是為已經(jīng)存在的類添加方法媒殉。通過Category可以把類的實現(xiàn)分開在幾個不同的文件里面,這樣做一是可以減少單個文件的體積摔敛,二是可以把不同的功能組織到不同的Category里面廷蓉,三是可以按需加載想要的Category 等等。
一般我們修改某一個frame屬性的時候都需要比較繁瑣的代碼書寫马昙,這樣既費時費力桃犬,并且工程量較大的時候也會減弱代碼的可讀性,因此我們可以通過建立UIView的類別Category來實現(xiàn)修改frame屬性的簡單操作行楞。
1.創(chuàng)建類別
(1)UIView+SHK.h
.h文件定義的屬性可以根據(jù)自己需求添加
#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文件實現(xiàn)各個屬性的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)簡單的使用示例
導(dǎo)入頭文件進行使用,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
小結(jié)
以上方法是針對近期自學(xué)新浪微博項目的一點小小總結(jié)子房,行筆簡陋形用,如有錯誤就轧,望指正。