代码之家  ›  专栏  ›  技术社区  ›  Lope

如何在uilabel上获得“取消选择”通知

  •  3
  • Lope  · 技术社区  · 14 年前

    我有uilabel,我需要它能够支持复制和粘贴(实际上只复制,因为它是只读的)。我对uilabel进行了子类化以支持copy,它工作得很好。我还添加了文本突出显示,这样用户在单击标签时就知道他到底在复制什么。

    我的问题是,当用户单击其他地方时,我不知道如何取消突出显示。复制气泡消失,但我没有收到任何回调,因此文本保持突出显示。有没有特别的回拨我错过了,我可以使用,还是我必须想出一些肮脏的黑客?或者,是否有更标准的方法来突出显示uilabel中的文本,我不知道这会像复制气泡一样自动处理?

    这里是我的自定义uilabel代码:

    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
        if(action == @selector(copy:)) {
            return YES;
        }
        else {
            return [super canPerformAction:action withSender:sender];
        }
    }
    
    - (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];
    
            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]) {
            //UIMenuController *menu = [UIMenuController sharedMenuController];
            //[menu setMenuVisible:NO animated:YES];
            //[menu update];
            [self resignFirstResponder];
        }
        else if([self becomeFirstResponder]) {
            //UIMenuController *menu = [UIMenuController sharedMenuController];
            //[menu setTargetRect:self.bounds inView:self];
            //[menu setMenuVisible:YES animated:YES];
        }
    }
    
    - (void)setHighlighted:(BOOL)hl {
        [super setHighlighted:hl];
    
        [self setNeedsLayout];
    }
    
    - (void)drawRect:(CGRect)rect {
        [super drawRect:rect];
    
        if(self.highlighted) {
            CGContextRef ctx = UIGraphicsGetCurrentContext();
            CGContextSetRGBFillColor(ctx, 0.3, 0.8, 1.0, 0.3);
            CGContextAddRect(ctx, CGRectMake(0, 0, [self textRectForBounds:self.frame limitedToNumberOfLines:1].size.width, self.frame.size.height));
            CGContextFillPath(ctx);
        }
    }
    

    感谢您的帮助!

    1 回复  |  直到 14 年前
        1
  •  2
  •   Nick Hingston    14 年前