我有一个位于屏幕底部的文本字段。当我开始编辑时,键盘出现并隐藏了 textField。
谁能建议如何解决这个问题?
通常,您会将内容放在滚动视图中,并在键盘出现时向上移动滚动视图。那里有很多教程,所以谷歌他们。Here
是其中之一。
您可以在两种不同的方法中使用以下代码,在编辑开始和结束时调用它,以上下移动视图,(只需根据需要更改减去的值yourView.frame.origin.y-100
即可调整)
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.5];
yourView.frame = CGRectMake(yourView.frame.origin.x, yourView.frame.origin.y-100, yourView.frame.size.width, yourView.frame.size.height);
[UIView commitAnimations];
请参阅此代码段。并使用一个 UIButton 来关闭 UIKeyboard。
- (void) animateTextField: (UITextField *)textField up:(BOOL) up
{
const int movementDistance = 200;
const float movementDuration = 0.4f;
int movement = (up ? -movementDistance : movementDistance);
up ? (self.button.enabled= YES) : (self.button.enabled = NO);
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
-(void)textFieldDidBeginEditing:(UITextField*) inTextField
{
[self animateTextField:mText up:YES];
[self addObservers];
}
- (void)addObservers
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:@"UITextFieldTextDidChangeNotification" object:nil];
}
- (void)textFieldDidChange:(NSNotification*)aNotification
{
NSLog(@"TextField data=%@",mText.text);
}
- (IBAction) doneBtn:(id)sender
{
[mText resignFirstResponder ];
[self animateTextField:mText up:NO];
}
当您向上点击 textField 键盘时,您的 textField 会被它隐藏。所以你需要什么,你需要让你的观点而不是keyboardresign是一个解决方案。所以为了让你查看使用
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField delegate for the logic. now see the code
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(textField.tag==1) //add tag to your textField to identify it
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.3];
CGRect viewFrame=self.view.frame;
viewFrame=sinViewFrame.size.height+100;
viewFrameorigin.y-=100; // as required
self.view.frame=viewFrame;
[UIView commitAnimations];
}
}
希望它可以帮助你。
我使用自动布局约束来解决这个问题。我将约束作为一个属性,并在键盘出现/消失时使用它。我只是将文本字段上方的视图移出屏幕,并将文本字段移到顶部。完成编辑后,我通过约束将它们移动到它们的原始位置。
-(void)keyboardWillShow:(NSNotification*)notification{
[UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
self.topSpaceLayoutConstraint.constant = -150;
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
} completion:NULL];
}
-(void)keyboardWillHide:(NSNotification*)notification
{
[UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
self.topSpaceLayoutConstraint.constant = 10;
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
} completion:NULL];
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpaceLayoutConstraint;