iOS - Moving a UITextField to a Different Position

2019-03-31 11:52发布

问题:

I have a main UIView which moves up by means of a switch. I have this working and there is no problem there. Now the UIView when down, takes up about half of the Screen and when it is pushed up it shows the bottom 40px.

In the UIView when it is down it has a UITextField and it sits somewhere in the middle. When the UIView is pushed up I want that UITextField to move to sit within those 40px, so that it always accessible.

This is the code I got for the UIView to move:

-(IBAction)mainview:(id)sender{

if (uiSwitch.on) {
    label.text = @"Push Up View";
    [UIView beginAnimations:@"animateView" context:nil];
    [UIView setAnimationDuration:0.5];
    CGRect viewFrame = [subView frame];
    viewFrame.origin.y  += 0;
    subView.frame = viewFrame;
    subView.alpha = 1.0; 
    [self.view addSubview:subView];
    [UIView commitAnimations];
}

if ([uiSwitch isOn] == YES) {
    [UIView beginAnimations:@"animateView" context:nil];
    [UIView setAnimationDuration:0.5];      
    CGRect viewFrame = [subView frame];
    viewFrame.origin.y  = 0;
    subView.frame = viewFrame;    
    [UIView commitAnimations];
}
else {
    label.text = @"Show View";   
    [UIView beginAnimations:@"returnView" context:nil];
    [UIView setAnimationDuration:0.5];  
    CGRect viewFrame = [subView frame];
    viewFrame.origin.y  = -230;
    subView.frame = viewFrame; 
    subView.alpha = 1.0;
    [UIView commitAnimations];
}}

The UITextField is not added to this yet and that is where I am stuck. I know I will probably have to create a similar IBAction for the UITextField, but I am not sure how to animate that bit.

Any Help??? Cheers Jeff

回答1:

You can animate multiple views at the same time. Your code:

label.text = @"Show View";   
[UIView beginAnimations:@"returnView" context:nil];
[UIView setAnimationDuration:0.5];  
CGRect viewFrame = [subView frame];
viewFrame.origin.y  = -230;
subView.frame = viewFrame; 
subView.alpha = 1.0;
[UIView commitAnimations];

.. can include additional frame manipulations on your UITextField:

label.text = @"Show View";   
[UIView beginAnimations:@"returnView" context:nil];
[UIView setAnimationDuration:0.5];  
CGRect viewFrame = [subView frame];
viewFrame.origin.y  = -230;
subView.frame = viewFrame; 
subView.alpha = 1.0;
// let's move our textField too
CGRect textFieldFrame=textField.frame;
frame.origin.y+=40;
textField.frame=textFieldFrame;
[UIView commitAnimations];

Note that if you're targeting iOS 4.x or later, you can rely on animation blocks:

[UIView animateWithDuration:0.5 animations:^{

    CGRect frame;

    // move our subView to its new position
    frame=subView.frame;
    frame.origin.y=-230;
    subView.frame=frame;
    subView.alpha=1.0;

    // let's move our textField too
    frame=textField.frame;
    frame.origin.y=40;
    textField.frame=frame;

}];