開發中經常會通過調節控件的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調整坐標了。