【问题标题】:Get input from a keyboard that is activated by a UILabel从由 UILabel 激活的键盘获取输入
【发布时间】:2014-03-08 20:29:11
【问题描述】:

当用户触摸UITableViewCellUICollectionViewCell 中的标签时,我可以激活键盘:

UITextField *tf = [[UITextField alloc] initWithFrame:[cell bounds]];
[tf setKeyboardType:UIKeyboardTypeNumberPad];
[cell.lblTest addSubview:tf];
[cell.lblTest setUserInteractionEnabled:YES];

[cell.lblTest setText:[NSString stringWithFormat:@"cell %d", indexPath.row]];

结果如下:

我的问题:

1) 我如何从键盘获取输入,以及

2) 当用户更改单元格选择时关闭键盘。

【问题讨论】:

  • 确保使用-tableView:(UITableView *)tableView didSelectCellAtIndex:(NSInteger)index 方法的UITableView delegate

标签: ios objective-c cocoa-touch uitextfield


【解决方案1】:

您可以成为文本字段的代表或收听特定文本字段的UITextFieldTextDidChangeNotification 通知以了解更改。要关闭键盘,请在文本字段中调用 resignFirstResponder

但这是一个糟糕的设计。您将越来越多的文本字段添加到视图层次结构中。您至少应该在关闭键盘时移除它们。 另外,你想达到什么目的?在没有向用户反馈按键输入(例如可见文本字段或文本视图)的情况下显示键盘不是一个很好的做法。

【讨论】:

  • 我同意这可能是一个糟糕的 UI 设计。这更像是一种技术可行性的练习。
【解决方案2】:

当用户点击您的文本字段时关闭键盘:

为您的文本字段添加一个 iboutlet

@property (weak, nonatomic) IBOutlet UITextField *textInput;

将此添加到您的视图控制器

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    if ([self.textInput isFirstResponder] && [touch view] != self.textInput) {
        [self.textInput resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];
}

【讨论】:

  • IBOutlet 用于 I 接口 B uilder outlets;他在代码中添加了文本字段。
  • @LeoNatan,所以,只是一个普通的属性:@property (strong, nonatomic) UITextField *textInput;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 2011-10-19
  • 2010-11-29
  • 2021-08-29
  • 1970-01-01
相关资源
最近更新 更多