frame属性对于每一个iOS开发者来说都不是陌生的,在开发中经常需要修改某个控件的位置和大小,但frame是结构体,我们是不能直接修改结构体里面的值.我们需要三个步骤才能修改一个frame,也就是大家常说的三部曲
CGRect frame = self.btn.frame;
frame.size.height += 20;
self.btn.frame = frame;
感觉非常麻烦,如果要修改的属性很多,会浪费非常多的时间.下面我来教大家一个非常爽的方法,可以直接修改属性,就像下面一样
self.btn.height += 20;
其实只要自己给UIView写个分类就好了,在分类中定义一些属性就可以了.
分类UIView+Frame 声明
#import <UIKit/UIKit.h>
@interface UIView (Frame)
// 自动生成get,set方法的声明,在分类里面用@property不会帮你自动生成带下划线的成员属性
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@end
分类UIView+Frame 实现
#import "UIView+Frame.h"
@implementation UIView (Frame)
- (void)setX:(CGFloat)x
{
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)x
{
return self.frame.origin.x;
}
- (void)setY:(CGFloat)y
{
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (CGFloat)y
{
return self.frame.origin.y;
}
- (void)setWidth:(CGFloat)width
{
CGRect frame = self.frame;
frame.size.width = width;
self.frame = frame;
}
- (CGFloat)width
{
return self.frame.size.width;
}
- (void)setHeight:(CGFloat)height
{
CGRect frame = self.frame;
frame.size.height = height;
self.frame = frame;
}
- (CGFloat)height
{
return self.frame.size.height;
}
@end
建好分类之后,以后需要用到的时候,把两个文件拖到工程里面,然后导入头文件,就可以用了