Alter CGRect (or any struct)?

后端 未结 3 1975

I do this quite a bit in my code:

self.sliderOne.frame  = CGRectMake(newX, 0, self.sliderOne.frame.size.width, self.sliderOne.frame.size.height); 

相关标签:
3条回答
  • 2021-01-06 07:32

    I finally followed @Dave DeLong's suggestion and made a category. All you have to do is import it in any class that wants to take advantage of it.

    UIView+AlterFrame.h

    #import <UIKit/UIKit.h>
    
    @interface UIView (AlterFrame)
    
    - (void) setFrameWidth:(CGFloat)newWidth;
    - (void) setFrameHeight:(CGFloat)newHeight;
    - (void) setFrameOriginX:(CGFloat)newX;
    - (void) setFrameOriginY:(CGFloat)newY;
    
    @end
    

    UIView+AlterFrame.m

    #import "UIView+AlterFrame.h"
    
    @implementation UIView (AlterFrame)
    
        - (void) setFrameWidth:(CGFloat)newWidth {
            CGRect f = self.frame;
            f.size.width = newWidth;
            self.frame = f;
        }
    
        - (void) setFrameHeight:(CGFloat)newHeight {
            CGRect f = self.frame;
            f.size.height = newHeight;
            self.frame = f;
        }
    
        - (void) setFrameOriginX:(CGFloat)newX {
            CGRect f = self.frame;
            f.origin.x = newX;
            self.frame = f;
        }
    
        - (void) setFrameOriginY:(CGFloat)newY {
            CGRect f = self.frame;
            f.origin.y = newY;
            self.frame = f;
        }
    
    @end
    

    I could DRY up the methods using blocks... I'll do that at some point soon, I hope.

    Later: I just noticed CGRectOffset and CGRectInset, so this category could be cleaned up a bit (if not eliminated altogether).

    0 讨论(0)
  • 2021-01-06 07:38

    The issue here is that self.sliderOne.frame.origin.x is the same thing as [[self sliderOne] frame].origin.x. As you can see, assigning back to the lValue here is not what you want to do.

    So no, that "tedious" code is necessary, although can be shortened up a bit.

    CGRect rect = thing.frame;
    thing.frame = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect) + 10, etc...);
    
    0 讨论(0)
  • 2021-01-06 07:45

    Yeah, you have to do:

    CGRect newFrame = self.sliderOne.frame;
    newFrame.origin.x = frame.size.width - MARGIN * 2 - totalWidth;
    self.sliderOne.frame = newFrame;
    

    It sucks, I know. If you find yourself doing this a lot, you may want to add categories to UIView/NSView to alter this stuff for you:

    @interface UIView (FrameMucking)
    
    - (void) setWidth:(CGFloat)newWidth;
    
    @end
    
    @implementation UIView (FrameMucking)
     - (void) setWidth:(CGFloat)newWidth {
      CGRect f = [self frame];
      f.size.width = newWidth;
      [self setFrame:f];
    }
    @end
    

    Etc.

    0 讨论(0)
提交回复
热议问题