工具类:快速获取控件 frame 值(UIView 分类)

.h

// 分类:不能添加属性 (使用runtime可以实现添加属性)
@interface UIView (XXXXExp)
// 所有都只是声明了setter 和 getter 方法,并没有新增属性
@property (nonatomic, assign) CGFloat x; // 声明setter 和 getter
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@end

.m


@implementation UIView (XXXXExp)
// 有没有新增属性名为x的属性?
- (void)setX:(CGFloat)x {
    // 如果有x 属性存在
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (CGFloat)x {
    CGFloat x = self.frame.origin.x;
    return 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

你可能感兴趣的:(代码工具)