为UitextField设置inputAccessoryView

时间:2015-03-25 13:17:52

标签: ios objective-c iphone

我只想让键盘出现时UITextField上升。我通过在键盘出现后设置UITextField的框架来实现它。它适用于普通案件。但是,如果用户在默认键盘中启用了预测,那么预测文本区域将被放置在UITextField之上。在这种情况下,我希望文本字段向上移动。我尝试设置textfield的inputAccessoryView。但应用程序崩溃时没有报告。那么如何设置textA的inputAccessoryView来满足我的要求。

textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, bottomToolbarView.frame.size.width, bottomToolbarView.frame.size.height)];
textField.delegate = self;
textField.textAlignment = NSTextAlignmentCenter;
textField.inputAccessoryView = bottomToolbarView;
[textField setReturnKeyType:UIReturnKeyGo];
[textField setPlaceholder:@"Enter Employee Id"];
[textField setBackgroundColor:[UIColor colorWithRed:1.000 green:0.720 blue:0.611 alpha:1.000]];
[bottomToolbarView addSubview:textField];

Simulator Image

1 个答案:

答案 0 :(得分:0)

在文本字段中尝试此代码。开始编辑委托方法

CGRect textFieldRect =
[self.view.window convertRect:textField.bounds fromView:textField];
CGRect viewRect =
[self.view.window convertRect:self.view.bounds fromView:self.view];

CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;

CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size. height;

CGFloat denominator =
(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;

CGFloat heightFraction = numerator / denominator;

if (heightFraction < 0.0)
{
    heightFraction = 0.0;
}
else if (heightFraction > 1.0)
{
    heightFraction = 1.0;
}

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

if (orientation == UIInterfaceOrientationPortrait ||
    orientation == UIInterfaceOrientationPortraitUpsideDown)
{
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
}
else
{
    animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
}

CGRect viewFrame = self.view.frame;
viewFrame.origin.y -= animatedDistance;

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

[self.view setFrame:viewFrame];

[UIView commitAnimations];

&安培; on didEndEditing委托方法

-(void)textFieldDidEndEditing:(UITextField *)textField1
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;

   [UIView beginAnimations:nil context:NULL];
   [UIView setAnimationBeginsFromCurrentState:YES];
   [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

   [self.view setFrame:viewFrame];
   [UIView commitAnimations];

}