Domanda

Im aware I can change the position of my image view like this

myImageView.frame = CGRectMake(99, 34, 32, 32);

But how do I change just the x value leave the rest as they are? I realize this is a simple question but because I don't know how to word the search Im having difficulty finding a solution. Thanks

È stato utile?

Soluzione

//capture frame
CGRect thisRect = myImageView.frame;

//modify required frame parameter (.origin.x/y, .size.width/height)
thisRect.origin.x = 0;

//set modified frame to object
[myImageView setFrame:thisRect];

Altri suggerimenti

You have some solutions to this issue but usually, if you want to simplify, you end up using a category like UIView+Position (UIView+Position.h UIView+Position.m) or UIView Helpers. Although this might be an overkill.

Another alternative is to use CGRect auxiliary methods like this:

myImageView.frame = CGRectOffset(myImageView.frame, 10, 0);

For more information on solutions for this problem read this post.

@staticVoidMan basically already said it, but if you want to keep the current scope clean and not pollute it with temporary variables, you can take advantage of a GCC extension and do this:

[self.view setFrame:({

    CGRect frame = [self.view frame];
    frame.origin.x = 0;
    frame;

})];

Note that while I said it's a GCC extension, it works fine with Clang (which, for the most parts, is compatible with GCC when it comes to these things).

Create a new rectangle and modify the parts you want, then assign the frame to that one.

CGRect newFrame = myImageView.frame;
newFrame.origin.x = 49;

myImageView.frame = newFrame;

You can access the width similarly:

newFrame.size.width = 55;

etc.

A Swift alternative using an extension can be found here. Example from above:

myImageView.x = 99

or

myImageView.left = 99

In Swift you can now do:

view.frame = view.frame.offsetBy(dx: 0, dy: -100)

to shift up.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top