UIView中frame的封装(方便使用x,y,width,height,center,size等)

  新建一个继承自UIView的分类

  在.h文件中写代码:

1 @property (assign, nonatomic)CGSize size;
2 @property (assign, nonatomic)CGFloat width;
3 @property (assign, nonatomic)CGFloat height;
4 @property (assign, nonatomic)CGFloat x;
5 @property (assign, nonatomic)CGFloat y;
6 @property (assign, nonatomic)CGFloat centerX;
7 @property (assign, nonatomic)CGFloat centerY;

  在.m文件中

 1 - (void)setSize:(CGSize)size
 2 {
 3     CGRect frame = self.frame;
 4     frame.size = size;
 5     self.frame = frame;
 6 }
 7 - (CGSize)size
 8 {
 9     return self.frame.size;
10 }
11 
12 - (void)setWidth:(CGFloat)width
13 {
14     CGRect frame = self.frame;
15     frame.size.width = width;
16     self.frame = frame;
17 }
18 - (CGFloat)width
19 {
20     return self.frame.size.width;
21 }
22 - (void)setHeight:(CGFloat)height
23 {
24     CGRect frame = self.frame;
25     frame.size.height = height;
26     self.frame = frame;
27 }
28 - (void)setX:(CGFloat)x
29 {
30     CGRect frame = self.frame;
31     frame.origin.x = x;
32     self.frame = frame;
33 }
34 - (void)setY:(CGFloat)y
35 {
36     CGRect frame = self.frame;
37     frame.origin.y = y;
38     self.frame = frame;
39 }
40 
41 - (CGFloat)height
42 {
43     return self.frame.size.height;
44 }
45 - (CGFloat)x
46 {
47     return self.frame.origin.x;
48 }
49 - (CGFloat)y
50 {
51     return self.frame.origin.y;
52 }
53 - (void)setCenterX:(CGFloat)centerX
54 {
55     CGPoint center = self.center;
56     center.x = centerX;
57     self.center = center;
58 }
59 - (void)setCenterY:(CGFloat)centerY
60 {
61     CGPoint center = self.center;
62     center.y = centerY;
63     self.center = center;
64 }
65 - (CGFloat)centerX
66 {
67     return self.center.x;
68 }
69 - (CGFloat)centerY
70 {
71     return self.center.y;
72 }

  如果把它导入放到PCH文件中,则整个项目所有文件夹都可以直接使用,比如想设置某个控件的尺寸:

button.x  button.y  button.width  label.centerX  label.size等等,所以上面封装过的属性都可以直接点出来

posted @ 2016-07-03 07:51  hissia  阅读(780)  评论(2编辑  收藏  举报