iOS UIView分类调整控件坐标

2018 年 1 月 15 日 0 条评论 1.63k 次阅读 0 人点赞

开发中经常会通过调节控件的frame设置控件的显示位置,经常拿到某个控件的frame,然后修改它的属性,比如.x .y .width .height等,修改后再赋值给控件。这样写没问题,可是有没有比较懒的方法呢,就是写一次之后再不用重复写了。这时候,我们应该想到分类(Catagory)

UIView+Ex.h


#import <UIKit/UIKit.h>

@interface UIView (Ex)
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;


@end

UIView+Ex.m


#import "UIView+Ex.h"

@implementation UIView (Ex)
//重写x属性的 getter方法,返回控件的x值
- (CGFloat)x{
    return self.frame.origin.x;
}
//重写x属性的 setter方法  设置控件的x值
- (void)setX:(CGFloat)x{
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}


- (CGFloat)y{
    return self.frame.origin.y;
}

- (void)setY:(CGFloat)y{
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}


- (CGFloat)width{
    return self.frame.size.width;
}

- (void)setWidth:(CGFloat)width{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)height{
    return self.frame.size.height;
}

- (void)setHeight:(CGFloat)height{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}
@end


UIViewController类导入分类后,UIView极其子类(如UIButton)就可以直接.x .y .width .height调整坐标了。

雷雷

这个人太懒什么东西都没留下

文章评论(0)

(Spamcheck Enabled)