开发中经常会通过调节控件的frame设置控件的显示位置,经常拿到某个控件的frame,然后修改它的属性,比如.x .y .width .height等,修改后再赋值给控件。这样写没问题,可是有没有比较懒的方法呢,就是写一次之后再不用重复写了。这时候,我们应该想到分类(Catagory)
UIView+Ex.h
#import <UIKit/UIKit.h>
@interface UIView (Ex)
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@end
UIView+Ex.m
#import "UIView+Ex.h"
@implementation UIView (Ex)
//重写x属性的 getter方法,返回控件的x值
- (CGFloat)x{
return self.frame.origin.x;
}
//重写x属性的 setter方法 设置控件的x值
- (void)setX:(CGFloat)x{
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)y{
return self.frame.origin.y;
}
- (void)setY:(CGFloat)y{
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (CGFloat)width{
return self.frame.size.width;
}
- (void)setWidth:(CGFloat)width{
CGRect frame = self.frame;
frame.size.width = width;
self.frame = frame;
}
- (CGFloat)height{
return self.frame.size.height;
}
- (void)setHeight:(CGFloat)height{
CGRect frame = self.frame;
frame.size.height = height;
self.frame = frame;
}
@end
UIViewController类导入分类后,UIView极其子类(如UIButton)就可以直接.x .y .width .height调整坐标了。