代码之家  ›  专栏  ›  技术社区  ›  Dan J Akhil

如何找出导致UIKeyboardWillShowNotification的UITextField?

  •  15
  • Dan J Akhil  · 技术社区  · 15 年前

    我的代码基于 this Xcode project (最初发现于 this blog ). 该代码将自定义的UIButton(表示“小数点”)添加到UIKeyboardTypeNumberPad键盘视图中。它通过订阅UIKeyboardWillShowNotification并在键盘出现时对其进行修改来实现。

    Xcode项目工作得很好,但是当我添加一个额外的UITextField时,自定义键也会放入该文本字段的键盘中,即使我为该文本字段选择了完全不同的键盘类型。

    我试图注册只查看来自一个特定UITextField的UIKeyboardWillShowNotification通知,但这似乎不起作用:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:exampleViewController.textField];
    

    我还试图检查传递给keyboardWillShow的NSNotification中的对象,但不幸的是它指的是键盘,而不是导致键盘出现的UI控件。

    2009-10-21 19:50:22.205 Example[6302:207] NSConcreteNotification 0x321ebd0 {name = UIKeyboardWillShowNotification; userInfo = {
    UIKeyboardAnimationCurveUserInfoKey = 0;
    UIKeyboardAnimationDurationUserInfoKey = 0.300000011920929;
    UIKeyboardBoundsUserInfoKey = NSRect: {{0, 0}, {320, 216}};
    UIKeyboardCenterBeginUserInfoKey = NSPoint: {160, 588};
    UIKeyboardCenterEndUserInfoKey = NSPoint: {160, 372};
    

    }}

    我是不是误解了addObserver接口?一定有办法订阅来自特定UI控件的通知吗?

    4 回复  |  直到 15 年前
        1
  •  25
  •   Ajay Gautam    14 年前

    不能让上面的任何一个工作。必须手动操作:

    if ([companyName isFirstResponder]) {
        // ...............
    }
    else if ([notes isFirstResponder]) {
        //.............
        }
    }
    
        2
  •  2
  •   berilcetin    9 年前

    - (UIView *)firstResponder
    {
        if ([self isFirstResponder])
        {
            return self;
        }
    
        for (UIView *view in self.subviews)
        {
            UIView *firstResponder= [view firstResponder];
            if (firstResponder)
            {
                return firstResponder;
            }
        }
    
        return nil;
    }
    

    然后在你的 - (void)keyboardWillShow:(NSNotification *)notification

      UITextField *textField = (UITextField *)[self firstResponder];
    
        3
  •  0
  •   Alex Reynolds    15 年前

    这个项目工作得很好,但是当我添加一个额外的UITextField时,自定义键也会被放入该文本字段的键盘中。

    您可以为 UITextField 实例,例如:

    [myTextField setKeyboardType:UIKeyboardTypeDefault];
    

    或:

    myTextField.keyboardType = UIKeyboardTypeDefault;
    

    搜索Xcode帮助 UITextInputTraits Protocol UIKeyboardType 常数。

        4
  •  -2
  •   John S. Eddie    14 年前

    if(notification.object == exampleViewController.textField)
    {
      ...
    }