带有UIMenucontroller的UILabel不会在外面触摸时让第一响应者退出

时间:2011-07-06 02:49:32

标签: iphone cocoa-touch uilabel

我已经将UILabel子类化为提供复制菜单,并希望添加某种类型的效果,使UILabel在显示此菜单时脱颖而出。

现在我正在尝试添加和删除边框。它工作正常但是如果用户触摸标签然后触摸标签之外,边框将不会消失,尽管复制菜单确实如此。

添加一些NSLog后,似乎没有在发生这种情况时调用resignfirstresponder。当发生这种情况时,响应者链中会发生什么?如何在此事件中使边界消失?

代码如下:

@implementation CopyLabel

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if(action == @selector(copy:)) {
        return YES;
    }
    else {
        return [super canPerformAction:action withSender:sender];
    }
}

- (BOOL) canBecomeFirstResponder {
    return YES;
}

- (BOOL)becomeFirstResponder {
    if([super becomeFirstResponder]) {
        self.highlighted = YES; 

        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setTargetRect:self.bounds inView:self];
        [menu setMenuVisible:YES animated:YES];

        return YES;
    }
    return NO;
}

- (BOOL)resignFirstResponder {
    if([super resignFirstResponder]) {
        self.highlighted = NO; 

        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setMenuVisible:NO animated:YES];
        [menu update];

        NSLog(@"Resign");
        return true;
    }
    return false;
}


- (void)copy:(id)sender {
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    [board setString:self.text];
    self.highlighted = NO;
    [self resignFirstResponder];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if([self isFirstResponder]) {
        [self resignFirstResponder];
    }
    else if([self becomeFirstResponder]) {

    } else {
        [self resignFirstResponder];
    }
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    self.layer.borderColor = [UIColor blueColor].CGColor;
    self.layer.borderWidth = 0.0;
    if(self.highlighted) {
        self.layer.borderWidth = 1.0;
    }
}


@end

1 个答案:

答案 0 :(得分:3)

UIMenuController发布UIMenuControllerDidHideMenuNotification。当您收听该通知时(使用NSNotificationCenter),您可以在适当的时间将resignFirstResponder发送到您的Label。

示例:

- (id)init... {
    ...
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(editMenuHidden)
                                                 name:UIMenuControllerDidHideMenuNotification 
                                               object:nil];
    ...
}

- (void)dealloc {
    ...
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                name:UIMenuControllerDidHideMenuNotification 
                                              object:nil];
    ...
}

- (void)editMenuHidden {
    [self resignFirstResponder];
}

...