目标c - 我将如何关闭键盘UITextField



我想知道如何处理在 UITextField 中关闭键盘,当我通过 Outlets 执行此操作时,我知道该怎么做,但现在我用这样的代码声明我的文本字段:

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
cell.accessoryType = UITableViewCellAccessoryNone;
UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 185, 30)];
playerTextField.adjustsFontSizeToFitWidth = YES;
playerTextField.textColor = [UIColor blackColor];
if([indexPath row] == 0) {
    playerTextField.placeholder = @"Server Address";
    playerTextField.keyboardType = UIKeyboardTypeDefault;
    playerTextField.returnKeyType = UIReturnKeyDone;
} else if([indexPath row] == 1){
    playerTextField.placeholder = @"Server Port";
    playerTextField.keyboardType = UIKeyboardTypeDecimalPad;
    playerTextField.returnKeyType = UIReturnKeyDone;
} else {
    playerTextField.placeholder = @"Password";
    playerTextField.keyboardType = UIKeyboardTypeDefault;
    playerTextField.returnKeyType = UIReturnKeyDone;
    playerTextField.secureTextEntry = YES;
}
playerTextField.backgroundColor = [UIColor clearColor];
playerTextField.autocorrectionType = UITextAutocorrectionTypeNo;
playerTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
playerTextField.textAlignment = UITextAlignmentLeft;
playerTextField.tag = 0;
playerTextField.clearButtonMode = UITextFieldViewModeNever;
[playerTextField setEnabled: YES];
[cell.contentView addSubview:playerTextField];

return cell;
}

我将如何管理它?

因为您的文本字段位于单元格内,所以您需要标记它,您已经是,但是我建议使用与0不同的东西。 然后,每当您需要辞职时(假设您知道要查找哪个单元格):

    UITextField *myField = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:myRow inSection:mySection]].contentView viewWithTag:myTag];
    [myField resignFirstResponder];

如果您不知道它是哪个单元格,则需要遍历所有单元格。

希望这有帮助

似乎您有很多文本字段,每个单元格中一个?

您需要添加属性@property (strong, nonatomic) UITextField *currentTextField

在 textField 创建方法中,您需要将表视图控制器设置为文本字段委托:

playerTextField.delegate = self;

然后,您必须使tableViewController实现UITextFieldDelegate协议(在头文件中的类名之后添加<UITextFieldDelegate>),然后为此方法添加实现:

- (void)textFieldDidBeginEditing:(UITextField *)textField {
     self.currentTextField = textField;
}

这意味着当其中一个文本字段开始编辑时,它会被跟踪。

可能您有事件或按钮可以调用类似(void)save操作。添加到其实现中:

- (void)save {
     [self.currentTextField resignFirstResponder];
}

您还可以跟踪文本字段完成编辑的时间:(void)textFieldDidEndEditing:(UITextField *)textField

最新更新