iOS — is it possible to force a UILabel subclass object to become the first responder?

懵懂的女人 提交于 2019-12-23 09:33:37

问题


Is there any way to do this?

I tried putting the following into the subclass:

- (BOOL)canBecomeFirstResponder 
{
    return YES;
}

But when I sent the object a becomeFirstResponder message, it still didn't become the first responder.


回答1:


Yes, it is possible. You should:

  1. Override becomeFirstResponder to return YES.

  2. Set userInteractionEnabled to YES.

  3. Add a UITapGestureRecognizer to handle taps.

  4. Call becomeFirstResponder from the tap handler.

You can even override inputView to get a input control at the bottom of the screen. Otherwise there will be nothing.




回答2:


I have no definite answer, just a few (maybe crazy) ideas: Have you also tried to override becomeFirstResponder to return YES? Does it have userInteractionEnabled also set to YES?

Otherwise, make it a custom UIButton instead of a custom UILabel...




回答3:


This worked for me.

Subclass UILabel and override these methods:

- (BOOL)canBecomeFirstResponder {
        return YES;
    }

    - (BOOL)canPerformAction:(SEL)action
                  withSender:(id)sender
    {
        return (action == @selector(copy:));
    }

    - (void)copy:(id)sender {
        [[UIPasteboard generalPasteboard] setString:self.text];
    }

Add Gesture to your label to detect tap.

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

Handle gesture event, present a UIMenuController with the desired frame:

- (void)LongPressDetected:(UILongPressGestureRecognizer*)gesture {

        [_messageLabel becomeFirstResponder];
        [[UIMenuController sharedMenuController] setTargetRect:_messageLabel.bounds inView:_messageLabel];
        [[UIMenuController sharedMenuController] setMenuVisible:YES animated:NO];
    }


来源:https://stackoverflow.com/questions/4089682/ios-is-it-possible-to-force-a-uilabel-subclass-object-to-become-the-first-res

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!