对象:当键盘激活时,将uitextview移位?

时间:2017-10-22 01:48:39

标签: ios objective-c

当我的用户输入我的textview时,我希望textview向上移动,以便键盘不会覆盖它。我使用下面的代码,但没有任何东西向上移动,键盘继续覆盖我的textview。我该如何解决这个问题?

ViewController.h

 @property (strong, nonatomic) IBOutlet UITextView *replyField;

ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];


[self.replyField setReturnKeyType:UIReturnKeyDefault];

}

- (void)dismissKeyboard
{
    [self.replyField resignFirstResponder];

}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [self animateTextView: YES];
}


- (void)textViewDidEndEditing:(UITextView *)textView
{
    [self animateTextView:NO];
}

- (void) animateTextView:(BOOL) up
{
    const int movementDistance = -250; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    int movement= movement = (up ? -movementDistance : movementDistance);
    NSLog(@"%d",movement);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
    [UIView commitAnimations];
}

1 个答案:

答案 0 :(得分:0)

animateTextView方法中看到有2个错误:

  • 原始值-250导致(up ? -movementDistance : movementDistance)

  • 的移动方向错误
  • self.view.frame = CGRectOffset(self.inputView.frame, 0, movement); 将改变self.view的框架,而不是textView的。

改进(在我的Xcode中测试的代码):

- (void)textViewDidBeginEditing:(UITextView *)textView{
    [self animateTextView:textView isUp:YES];
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    [self animateTextView:textView isUp:NO];
}

- (void)animateTextView:(UITextView *)textView isUp:(BOOL)up{
    const int movementDistance = 250; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed
    int movement = (up ? -movementDistance : movementDistance);
    NSLog(@"%d",movement);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    textView.frame = CGRectOffset(textView.frame, 0, movement);
    [UIView commitAnimations];
}

//To close keyboard when click Return key.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

和@El Tomato说的一样,记得为textView设置委托:

[self.replyField setDelegate:self];