UIView的frame的扩展分类,轻松取出x、y、height、width等值

一、引言:

在ios开发中,就界面搭建、控件布局时,都会很恶心的通过很长的代码才能取出控件的x、y、height、width等值,大大降低了开发效率。那为了省略这些恶心的步骤,小编在这里给UIView添加了一个关于frame的扩展分类。

 

二、添加了分类之后的效果对比

1、未添加分类前取值:

    self.view.frame.size.width;
    self.view.frame.size.height;
    self.view.frame.origin.x;
    self.view.frame.origin.y;

2、添加了分类之后取值:

    self.view.height;
    self.view.width;
    self.view.x;
    self.view.y;
    self.view.size;

 

三、添加分类操作:

1、添加分类:

    说明:在分类中通过@property添加属性时,只能声明属性及其set、get方法,但没有实现其set、get方法,需要自己实现:set、get方法

#import <UIKit/UIKit.h>

@interface UIView (ICKExtensionOfFrame)

@property (nonatomic,assign) CGFloat x;
@property (nonatomic,assign) CGFloat y;
@property (nonatomic,assign) CGFloat width;
@property (nonatomic,assign) CGFloat height;
@property (nonatomic,assign) CGSize size;

@end
 1 #import "UIView+ICKExtensionOfFrame.h"
 2 
 3 @implementation UIView (ICKExtensionOfFrame)
 4 /**
 5  *  x 的set\get方法实现
 6  */
 7 - (void)setX:(CGFloat)x
 8 {
 9     CGRect rect = self.frame;
10     rect.origin.x = x;
11     self.frame = rect;
12 }
13 - (CGFloat)x
14 {
15     return self.frame.origin.x;
16 }
17 
18 /**
19  *  y 的set\get方法实现
20  */
21 - (void)setY:(CGFloat)y
22 {
23     CGRect rect = self.frame;
24     rect.origin.y = y;
25     self.frame = rect;
26 }
27 - (CGFloat)y
28 {
29     return self.frame.origin.y;
30 }
31 
32 /**
33  *  width 的set\get方法实现
34  */
35 - (void)setWidth:(CGFloat)width
36 {
37     CGRect rect = self.frame;
38     rect.size.width  =  width;
39     self.frame = rect;
40 }
41 - (CGFloat)width
42 {
43     return self.frame.size.width;
44 }
45 
46 /**
47  *  height 的set\get方法实现
48  */
49 - (void)setHeight:(CGFloat)height
50 {
51     CGRect rect = self.frame;
52     rect.size.height = height;
53     self.frame = rect;
54 }
55 - (CGFloat)height{
56     return self.frame.size.height;
57 }
58 
59 /**
60  *  size 的set\get方法实现
61  */
62 - (void)setSize:(CGSize)size
63 {
64     CGRect rect = self.frame;
65     rect.size = size;
66     self.frame = rect;
67 }

2、将其头文件导入项目的.pch

#import "UIView+ICKExtensionOfFrame.h"

3、在此项目中的任何控件的frame的属性取值,都可以直接取出。

posted @ 2015-07-25 18:15  *码是一种情怀  阅读(1188)  评论(0)    收藏  举报