键盘外观时将textView / textField移动到顶部

时间:2014-08-13 09:14:22

标签: ios text textview uitextfield

当我选择其中一个时,如何将textView / textField移到顶部?

1 个答案:

答案 0 :(得分:2)

工作代码......

1)将delegate设置为textFields

[self.textField setDelegate:self];

2)向上移动textField

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.textField)
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationBeginsFromCurrentState:YES];
        self.view.frame = CGRectMake(self.view.frame.origin.x , (self.view.frame.origin.y - 80), self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

3)向下移动textField

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == self.textField)
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationBeginsFromCurrentState:YES];
        self.view.frame = CGRectMake(self.view.frame.origin.x , (self.view.frame.origin.y + 80), self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

4)向上移动textView

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if (textView == self.textView)
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationBeginsFromCurrentState:YES];
        self.view.frame = CGRectMake(self.view.frame.origin.x , (self.view.frame.origin.y - 80), self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

5)向下移动textView

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView == self.textView)
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationBeginsFromCurrentState:YES];
        self.view.frame = CGRectMake(self.view.frame.origin.x , (self.view.frame.origin.y + 80), self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}