UIView+Extension方便在开发时快速修改视图的位置大小

 在做iOS开发时,我们经常需要设定某个控件的大小,位置,通常我们采用的方法是用CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>);来设置位置坐标,和自身的宽高,然后在赋值个控件的frame,这样做太麻烦,在一个项目里添加有一个UIview的分类,在分类里定义一些属性如下图所示

把头文件放到你的整个项目的头文件中就可以了,在任何地方使用时是需要点出来就行

  UIButton *btn = [[UIButton alloc] init];
    btn.x = 100;
    btn.y = 100;
    btn.height = 50;
    btn.width = 80;
    btn.centerX = 200;
    btn.centerY = 200;

这样就能轻易地设置一个空间的frame,如果需要修改其中的一个值也不用去重复设置其他三个值。

源码如下:

UIView+Extension.h的头文件

#import <UIKit/UIKit.h>

@interface UIView (Extension)
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat centerX;
@property (nonatomic, assign) CGFloat centerY;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGSize size;
@end

UIView+Extension.m

#import "UIView+Extension.h"

@implementation UIView (Extension)

- (void)setX:(CGFloat)x
{
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

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

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

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

- (void)setCenterX:(CGFloat)centerX
{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

- (CGFloat)centerX
{
    return self.center.x;
}

- (void)setCenterY:(CGFloat)centerY
{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

- (CGFloat)centerY
{
    return self.center.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;
}

- (void)setSize:(CGSize)size
{

    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (CGSize)size
{
    return self.frame.size;
}

@end

 

posted @ 2016-04-11 20:04  笑对人生1229  阅读(1499)  评论(1编辑  收藏  举报