【问题标题】:iOS -- is it possible to force a UILabel subclass object to become the first responder?iOS——是否可以强制 UILabel 子类对象成为第一响应者?
【发布时间】:2010-11-03 17:15:35
【问题描述】:

有什么办法吗?

我尝试将以下内容放入子类中:

- (BOOL)canBecomeFirstResponder 
{
    return YES;
}

但是当我向对象发送 becomeFirstResponder 消息时,它仍然没有成为第一响应者。

【问题讨论】:

  • UILabel 成为第一响应者?你希望它回应什么?
  • 它继承自 UIResponder 所以它确实有这个能力。
  • 我正在使用某人的库,当具有某些属性的对象成为第一响应者时,它会做一些事情。它还向第一响应者发送消息。我碰巧想把这一切都和我的标签联系起来。

标签: iphone ios first-responder


【解决方案1】:

是的,这是可能的。你应该:

  1. 覆盖becomeFirstResponder 以返回YES

  2. userInteractionEnabled 设置为YES

  3. 添加UITapGestureRecognizer 来处理水龙头。

  4. 从点击处理程序调用becomeFirstResponder

您甚至可以覆盖inputView 以获得屏幕底部的输入控件。否则什么都没有。

【讨论】:

  • 我应该返回inputView 以在屏幕上看到键盘?
  • @derpoliuk 感谢您的评论。我的错,没有检查 UIKeyboard 类是私有 API。
  • 所以UILabel 成为第一响应者后就没有办法在屏幕上显示键盘了吗?我试图模仿 Viber 或 Telegram 的行为,当键盘在屏幕上并且长按聊天消息时显示 UIMenuController
  • 不确定您的 UILabel 是否应该成为能够显示 UIMenuController 的第一响应者。你确定你负责屏幕键盘的 UITextField 在同一个 UIViewController 中吗?
  • 我打电话给[UILabel becomeFirstResponder]是因为UIMenuController。在这种情况下,UILabel 能够响应来自UIMenuControllercopy: 消息。如果我打电话给[UITextView becomeFirstResonder]UILabel 将无法再回复copy:。感谢您的回复。
【解决方案2】:

我没有明确的答案,只有几个(可能是疯狂的)想法:您是否也尝试过覆盖becomeFirstResponder 以返回YES?是否将userInteractionEnabled 也设置为YES

否则,将其设为自定义 UIButton 而不是自定义 UILabel...

【讨论】:

    【解决方案3】:

    这对我有用。

    子类 UILabel 并覆盖这些方法:

    - (BOOL)canBecomeFirstResponder {
            return YES;
        }
    
        - (BOOL)canPerformAction:(SEL)action
                      withSender:(id)sender
        {
            return (action == @selector(copy:));
        }
    
        - (void)copy:(id)sender {
            [[UIPasteboard generalPasteboard] setString:self.text];
        }
    

    将手势添加到您的标签以检测点击。

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongPressDetected:)];
    [_messageLabel addGestureRecognizer:longPress];
    

    处理手势事件,呈现一个带有所需帧的 UIMenuController:

    - (void)LongPressDetected:(UILongPressGestureRecognizer*)gesture {
    
            [_messageLabel becomeFirstResponder];
            [[UIMenuController sharedMenuController] setTargetRect:_messageLabel.bounds inView:_messageLabel];
            [[UIMenuController sharedMenuController] setMenuVisible:YES animated:NO];
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多