简体   繁体   中英

Dynamically changing position of a UIView

Here's my setup. I have a viewcontroller that I'm creating and adding as a subview. The viewcontroller presents some options that a user can chose from. The viewcontroller is being pushed in response to a "long press" gesture. Within the viewcontroller, I added a child UIView to group some other controls together so I can move them around the screen as a unit and, when they are displayed, center them on the location of the long press. Here is the code that instantiates the view controller, changes its location, and adds it as a subview:

UserOptions *opts = [[UserOptions alloc] initWithNibName:@"UserOptions" bundle:nil];
[opts recenterOptions:location];
[self.view addSubview:opts.view];

That bit of code does create and push the viewcontroller, but the call to recenterOptions doesn't do anything. Here is that method:

- (void) recenterOptions:(CGPoint)location {
    CGRect oldFrame = self.optionsView.frame;

    CGFloat newX = location.x; // + oldFrame.size.width / 2.0;
    CGFloat newY = location.y; // + oldFrame.size.height / 2.0;

    CGRect newFrame = CGRectMake(newX, newY, oldFrame.size.width, oldFrame.size.height);

    self.optionsView.frame = newFrame;
}

Note that self.optionsView is the child UIView that I added to the viewcontroller's nib.

Does anyone know why I'm unable to change the location of the UIView?

Regards, Eric

A couple things. First, try adding the view to the view hierarchy before calling -recenterOptions:

UserOptions *opts = [[UserOptions alloc] initWithNibName:@"UserOptions" 
                                                  bundle:nil];
[self.view addSubview:opts.view];
[opts recenterOptions:location];

Next, just set the center of the view instead of trying to change its frame:

- (void) recenterOptions:(CGPoint)location {
    [[self optionsView] setCenter:location];
}

Are you verifying that your optionsView is valid (non-nil)?

I agree with Rob, btw. You need to change your title to match your question.

Views are loaded lazily. Until you call self.view , the view is not loaded and optionsView is nil, hence self.optionsView.frame = newFrame does nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM