iOS frame change one property (eg width)

前端 未结 9 1032
日久生厌
日久生厌 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:59

    If you find yourself needing to do this sort of individual component modification, it may be worthwhile having macros like these somewhere accessible by all of your code:

    #define CGRectSetWidth(rect, w)    CGRectMake(rect.origin.x, rect.origin.y, w, rect.size.height)
    #define ViewSetWidth(view, w)   view.frame = CGRectSetWidth(view.frame, w)
    

    This way, whenever you need to change the width alone - you would simply write

    ViewSetWidth(self, 50);
    

    instead of

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, 50);
    
    0 讨论(0)
  • 2020-12-14 00:59

    Hope I am not too late to the party, here's my solution in ObjC.

    For me I prefer to stick to a single function instead of several functions, and I like the CSS approach shown by the poster. Below is the function I add to my UIView Category.

    - (void)resetFrame:(CGRect)frame {
    CGRect selfFrame = self.frame;
    selfFrame.origin = CGPointMake(frame.origin.x>0 ? frame.origin.x : selfFrame.origin.x, frame.origin.y>0 ? frame.origin.y : selfFrame.origin.y);
    selfFrame.size = CGSizeMake(frame.size.width>0 ? frame.size.width : selfFrame.size.width, frame.size.height>0 ? frame.size.height : selfFrame.size.height);
    [self setFrame:selfFrame]; }
    

    Shown in the example, it looks at each values in the provided CGRect, and if the value is more than 0, it means we want to replace that value. And therefore, you can do CGRect(0,0,100,0) and it will assume we want to replace the width only.

    0 讨论(0)
  • 2020-12-14 01:00

    In Swift you could extend the UIView class for the app, such that you could, for example, move the table header view up by 10 points like this:

        tableView.tableHeaderView!.frameAdj(0, -20, 0, 0)
    

    (of course if you're using AutoLayout, that might not actually do anything... :) )

    By extending UIView (affecting every UIView and subclass of it in your app)

    extension UIView {
        func frameAdj(x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) {
                self.frame = CGRectMake(
                    self.frame.origin.x + x,
                    self.frame.origin.y + y,
                    self.frame.size.width  + width,
                    self.frame.size.height + height)
        }
    }
    
    0 讨论(0)
提交回复
热议问题