Xcode:iPad键盘烦恼(不那么简单)

时间:2012-08-27 12:22:13

标签: xcode uitableview view keyboard ipad

我正在创建一个使用许多Textfields的应用程序。其中大多数都在静态tableViews中。我使用拆分视图应用程序模板。从左侧面板中选择的每个类别都会在右侧面板的第二个视图中显示故事板场景。 我只是想用“完成”按钮摆脱键盘,但是我尝试过的所有可以在简单视图上工作的东西都无法在这些情况下工作。 你能帮帮我吗?

P.S。我尝试在所呈现的故事板场景的实现文件中解除键盘。我应该在拆分视图控制器的详细信息场景中执行某些操作吗?

这是我的场景代码:

.h
    #import <UIKit/UIKit.h>
    @interface AfoEsoda : UITableViewController <UITextFieldDelegate>{
    }
    @property (strong, nonatomic) IBOutlet UITextField *merismataTF;
    -(IBAction)hideKeyboard:(id)sender;
    @end

.m
@synthesize merismataTF;

        - (void)viewDidLoad
        {
            [super viewDidLoad];
            merismataTF.delegate=self ;
        }

//---------Hide Keyboard-------------------
//Tried but didn't work
-(IBAction)hideKeyboard:(id)sender {
    [merismataTF resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
//Of course i do not use both methods at the same time.

编辑: 当我将textfield的委托设置为self时,我得到了这个崩溃: textfieldShouldReturn Crach

1 个答案:

答案 0 :(得分:1)

尝试实现textField的委托,将委托设置为self,并在委托的方法中

 - (BOOL)textFieldShouldReturn:(UITextField *)textField

设置

[textField resignFirstResponder];

另一种方式可能是浏览所有视图的子视图,如果是文本字段,请辞职第一响应者:

for(int i=0;i<self.view.subviews.count;i++)
{
if([[self.view.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
{
    if([[self.view.subviews objectAtIndex:i] isFirstResponder])
         [[self.view.subviews objectAtIndex:i] resignFirstResponder];
}}

好的,我明白了。与textFieldShouldReturn方法一起使用。 所以这是你的答案:你已经将你的文本字段声明为属性,然后使用alloc并为每个单元格反复初始化它。可能它只适用于最后一行。

以下是cellForRow方法的示例:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ static NSString *cellIdentifier = @"My cell identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITextField *newTextField;
if(cell == nil)
 {
  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
  newTextField = [[UITextField alloc] initWithFrame:CGRectMake:(0,0,25,25)];
  newTextField.tag = 1;
  newTextField.delegate = self;
  [cell.contentView addSubview:newTextField];
  }
  else
     newTextField = (UITextField *)[cell.contentView viewWithTag:1];

然后,如果您需要textField的值,请使用:

UITextField *someTextField = (UITextField *)[[tableView cellForRowAtIndexPath:indexPath].contentView viewWithTag:1];
NSLog(@"textField.text = %@", someTextField.text);