0

我正在制作一个使用许多文本字段的应用程序。它们中的大多数都在静态 tableViews 中。我使用拆分视图应用程序模板。从左侧面板中选择的每个类别都会在右侧面板的第二个视图中呈现故事板场景。我只想用“完成”按钮摆脱键盘,但是我尝试过的所有在简单视图上工作的东西在这些情况下都无法工作。你能帮我解决这个问题吗?

ps 我尝试在呈现的故事板场景的实现文件中关闭键盘。我应该在拆分视图控制器的细节场景中做些什么吗?

这是我的场景代码:

.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.

编辑:当我将文本字段的委托设置为 self 时,我遇到了这个崩溃: textfieldShouldReturn 崩溃

4

1 回答 1

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);
于 2012-08-27T13:49:11.437 回答