Domanda

In objective-c I am often updating the frames of my views during animations. I currently have a messy solution to doing so:

CGPoint newOrigin = CGPointMake(25.0, 25.0);    
view.frame = CGRectMake(newOrigin.x, newOrigin.y, view.frame.size.width, view.frame.size.height);

What I'm looking for is a simple convenience method that works like this:

view.frame = CGRectWithNewOrigin(view.frame, newOrigin);

Is there an existing method in the SDK which does this or will I need to define my own?

Solved: 0x7fffffff has the correct answer but JackWu's suggestion is a better approach:

The solution offered by Jack Wu solved my problem. The iOS SDK has no method which does this so you will need to define your own inline method to do so. However, utilizing the UIView's center property is a better approach. No need to define an inline function and it also will continue to work if the view has had a transform applied to it.

È stato utile?

Soluzione

It's easy enough to define a new inline method just like the ones already being used, like CGRectMake().. What about something like this?

static inline CGRect CGRectWithNewOrigin(CGPoint origin, CGRect frame) {
    return CGRectMake(origin.x, origin.y, frame.size.width, frame.size.height);
}

Then use it like you would for any other function of CGRect

CGPoint newOrigin = CGPointMake(25.0, 25.0); 
CGRect newRect = CGRectWithNewOrigin(newOrigin, oldRect);

Altri suggerimenti

CGRectOffset does the thing (in many but not all cases):

Returns a rectangle with an origin that is offset from that of the source rectangle.

This works:

view.frame = (CGRect){.origin = newOrigin, .size = view.frame.size};

Otherwise, you can just write your own C function, I'm pretty sure one doesn't exist. (I just looked at CGGeometry.h for the hundredth time.)

Though it's a little more general than what you are asking for, I've often thought something like this would be useful:

static inline CGRect CGRectFromOriginSize(CGPoint origin, CGSize size) {
    return (CGRect){.origin = newOrigin, .size = view.frame.size};;
}

This works fine:

CGRect newFrame = view.frame;

newFrame.origin = CGPointMake(25.0, 25.0);

view.frame = newFrame;

Try this:

CGPoint newOrigin = CGPointMake(25.0, 25.0);

CGRect newFrame = view.frame;
newFrame.origin = newOrigin;


view.frame = newFrame;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top