您好,我的应用程序中有两个 UITextField,当我触摸除 UITextField 之外的任何位置时,我想关闭键盘,我该怎么做?
10 回答
为此目的使用 tochesBegin 方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[yourFirstTextField resignFirstResponder];
[yourSecondTextField resignFirstResponder];
}
您不需要任何其他东西。当您触摸视图中的任何位置时,两个 textField 都无需知道哪个有焦点。当您触摸 textField 时,textField 会自行打开键盘。
伊修的回答很好。但我认为你也应该尝试一下:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
您需要在后台创建一个自定义按钮,然后将其连接到IBAction
调用resignFirstResponder
您的UITextField
像这样的东西
编辑:
因为您想以编程方式添加按钮而不是使用此代码
- (void)viewDidLoad
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
button.buttonType = UIButtonTypeCustom;
[button addTarget:self action:(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[button release];
然后在此之后添加您的控制器代码。
创建一个不可见的按钮,将其放在后面UITextField
并resignFirstResponder
在点击按钮时将消息发送到您的文本字段。
使用委托,
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
您还可以在控制器中创建一个方法
-(IBAction)editingEnded:(id)sender{
[sender resignFirstResponder];
}
然后在 IB 的 Connection Inspector 中将事件“Did End On Exit”连接到它。
通常在这种情况下,您将有一个滚动视图来保存用户界面的其余部分。如果您将该滚动视图的委托分配给您的视图控制器,并说您实现了协议UIScrollViewDelegate
,那么只需添加以下方法即可完成工作:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self.view endEditing:YES];
}
如果您不使用界面生成器,则可以按照此处的说明手动连接事件: 如何以编程方式将 UIView 或 UIImageView 与“内部修饰”之类的事件链接?
如果您使用的是界面生成器,则无需创建背景按钮。
你可以这样做:
- 选择您的视图(可能称为视图)
- 更改为属性检查器中的 (i) 选项卡
- 将类从 UIView 更改为 UIControl(这使您可以访问Touch Down事件)。
- 将Touch Down事件与您的 backgroundTap 方法挂钩(Ctrl + 拖动)。
- 不要忘记保存更改
You need to define the action for your button click this way
[infoButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];
And implement the click method ,as for example i have provided the animation on button click method.
-(void)backButtonClicked
{
[UIView beginAnimations:@"animation" context:nil];
[UIView setAnimationDuration:1.5];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
[self.navigationController popViewControllerAnimated:YES];
[UIView commitAnimations];
}
Hope this will help you ,the action is without using IB.Its all done through coding
用这个。
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 180; distace of keyboard up.
const float movementDuration = 0.3f;
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
在视图控制器中保留对 UITextField 的引用并调用 [yourTextField resignFirstResponder]