UIView+WKCategory

Foundouction框架里的frame属性是CGRect类型,CGRect是结构体,结构体类型里面的某个属性想修改是不能直接修改的,必须先取出来然后再重新赋值回去,完成三部曲,着实麻烦,确切的说一般是不能直接修改“对象的 结构体属性的 成员”,但能够修改“对象的 结构体属性”。

所以,解决方案,一般是把原有对象的结构体属性赋值给一个临时结构体,然后对临时结构体里地成员进行修改,然后把这个修改好的结构体变量直接赋值给原有对象的结构体变量,相当于修改了

UIView * view = [[UIView alloc]init];
view.frame.origin.x = 100;
CGRect frame = view.frame;
frame.origin.x = 100;
view.frame = frame;

category分类
UIView 多增加几个属性x,y,height,width。这几个属性都分别实现get方法和set方法。这样以后frame就可以离开他了,这样导入分类的所有继承UIView的类都有了这几个属性,可以直接对其尺寸和坐标赋值,不用引入中间变量,快捷方便

  • UIView+WKCategory.h

    #import 
     @interface UIView (WKCategory)
     @property (assign, nonatomic) CGFloat x;
     @property (assign, nonatomic) CGFloat y;
     @property (assign, nonatomic) CGFloat width;
     @property (assign, nonatomic) CGFloat height;
     @property (assign, nonatomic) CGSize size;
     @property (assign, nonatomic) CGPoint origin;
     @end
    
  • UIView+WKCategory.m
    #import "UIView+WKCategory.h"

      @implementation UIView (WKCategory)
    
        -(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)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;
        }
    
       - (void)setOrigin:(CGPoint)origin
           {
          CGRect frame = self.frame;
            frame.origin = origin;
           self.frame = frame;
          }
    
         - (CGPoint)origin
         {
          return self.frame.origin;
          }
    
          @end
    

你可能感兴趣的:(UIView+WKCategory)