iOS frame change one property (eg width)

前端 未结 9 1047
日久生厌
日久生厌 2020-12-14 00:20

This question was originally asked for the objective-c programming language. At the time of writing, swift didn\'t even exist yet.

Question

Is it po

9条回答
  •  太阳男子
    2020-12-14 00:36

    Based on ArtOfWarfare's solution (which is really awesome) I've build the UIView category without C-functions.

    Usage examples:

    [self setFrameWidth:50];
    self.frameWidth = 50;
    self.frameWidth += 50;
    self.frameWidth = otherView.frameWidth; // as opposed to self.frameWidth = otherView.frame.size.width;
    

    Header file UIView+easy_frame.h:

    @interface UIView (easy_frame)
    
    - (void) setFrameWidth:(CGFloat)width;
    - (void) setFrameHeight:(CGFloat)height;
    - (void) setFrameX:(CGFloat)x;
    - (void) setFrameY:(CGFloat)y;
    
    - (CGFloat) frameWidth;
    - (CGFloat) frameHeight;
    - (CGFloat) frameX;
    - (CGFloat) frameY;
    

    Implementation file UIView+easy_frame.m:

    #import "UIView+easy_frame.h"
    @implementation UIView (easy_frame)
    
    # pragma mark - Setters
    
    - (void) setFrameWidth:(CGFloat)width
    {
      self.frame = CGRectMake(self.frame.origin.x,
                              self.frame.origin.y,
                              width,
                              self.frame.size.height);
    }
    
    - (void) setFrameHeight:(CGFloat)height
    {
      self.frame = CGRectMake(self.frame.origin.x,
                              self.frame.origin.y,
                              self.frame.size.width,
                              height);
    }
    
    - (void) setFrameX:(CGFloat)x
    {
      self.frame = CGRectMake(x,
                              self.frame.origin.y,
                              self.frame.size.width,
                              self.frame.size.height);
    }
    
    - (void) setFrameY:(CGFloat)y
    {
      self.frame = CGRectMake(self.frame.origin.x,
                              y,
                              self.frame.size.width,
                              self.frame.size.height);
    }
    
    # pragma mark - Getters
    
    - (CGFloat) frameWidth
    {
      return self.frame.size.width;
    }
    
    - (CGFloat) frameHeight
    {
      return self.frame.size.height;
    }
    
    - (CGFloat) frameX
    {
      return self.frame.origin.x;
    }
    
    - (CGFloat) frameY
    {
      return self.frame.origin.y;
    }
    

提交回复
热议问题