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

Posted hissia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了十三: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等等,所以上面封装过的属性都可以直接点出来

以上是关于十三:UIView中frame的封装(方便使用x,y,width,height,center,size等)的主要内容,如果未能解决你的问题,请参考以下文章

用于直接设置原点和大小的 UIView 类别

视图UIView的大小和位置属性详解

UIView的layoutSubviews和drawRect方法何时调用

20160122UIView动画

滚动时在 UIPageController 中跟踪 frame.origin.x

自定义 UIView 类 - Swift