我有一个UITableView
有一些单元格UITextField
的单元格,我在每个单元格中添加了一个。
我设置textField.clearButtonMode = UITextFieldViewModeWhileEditing
。
当我编辑文本字段时,清除按钮和键盘都出来了。我在 textField 中键入一些单词,然后点击清除按钮,键盘将被隐藏,但 textField 中的文本不会被清除。
除清除按钮外,其他所有功能都运行良好。
我有一个UITableView
有一些单元格UITextField
的单元格,我在每个单元格中添加了一个。
我设置textField.clearButtonMode = UITextFieldViewModeWhileEditing
。
当我编辑文本字段时,清除按钮和键盘都出来了。我在 textField 中键入一些单词,然后点击清除按钮,键盘将被隐藏,但 textField 中的文本不会被清除。
除清除按钮外,其他所有功能都运行良好。
我遇到了这个问题,因为我忘记了我正在使用 aUITapGestureRecognizer
来捕捉桌面上的水龙头以关闭键盘,并且它正在捕捉清除按钮上的水龙头,从而阻止它运行。添加cancelsTouchesInView=NO
以UITapGestureRecognizer
使触摸仍然生效并检查使用轻敲CGRectContainsPoint
方法仅结束编辑并且resignFirstResponder
仅当轻敲不在当前UITextField
的框架矩形上时。请注意,这仍然不是完全完美的,因为在自动更正上点击 X 可能在文本字段的框架矩形之外,因此检查单元格contentView
可能会更好。
如果你有手势识别器,你应该这样做
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(methodThatYouMayCall)];
[myTextField addGestureRecognizer:gestureRecognizer];
gestureRecognizer.delegate = self;
gestureRecognizer.cancelsTouchesInView = NO;
当您单击清除按钮时,这将清除文本字段并触发“methodThatYouMayCall”,因此您也应该这样做,您的 textField.clearButtonMode 是一种 UIButton 类,因此您可以这样做
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if ([touch.view isKindOfClass:[UIButton class]])
{
return NO;
}
else
{
return YES;
}
}
不要忘记将类标记为实现 UIGestureRecognizerDelegate 协议。希望这会帮助你。
我无法重现您遇到的问题,因为触摸清除按钮不会也不应该让第一响应者辞职。但也许您可以将您的代码与我在下面包含的最基本用例进行比较,以找出问题所在。
此外,我建议您阅读有关UIResponder的文档,因为您似乎可能不小心涉足该领域。
@implementation TextFieldTableViewController
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
// Remove old instances of myTextField
for (UIView *oldView in cell.contentView.subviews)
[oldView removeFromSuperview];
// Create my new text field
UITextField *myTextField = [[UITextField alloc] initWithFrame:cell.contentView.bounds];
[myTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
[myTextField setBorderStyle:UITextBorderStyleRoundedRect];
// Add the TextField to the content view
[cell.contentView addSubview:myTextField];
return cell;
}
@end
虽然最初的问题不是由此引起的,但我认为任何未来的搜索都可能需要知道:
添加到 a 的视图UITableViewCell
必须作为子视图添加到其contentView
属性,否则您可能会遇到在未启用用户交互的情况下显示的视图。
contentView
自 iOS 2.0 以来,您应该添加子视图。