gpt4 book ai didi

iphone - 如何在 UILabel 上获取 "deselect"通知

转载 作者:行者123 更新时间:2023-12-03 20:00:34 24 4
gpt4 key购买 nike

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

我的问题是,当用户单击其他地方时,我不知道如何取消该突出显示。复制气泡消失,但我没有收到任何回调,因此文本保持突出显示。是否有我错过的特殊回调可以使用,或者我是否必须想出一些肮脏的技巧?或者是否有更标准的方法来突出显示 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);
}
}

感谢任何帮助!

最佳答案

就我个人而言,我会使用 UITextView,并将可编辑选项设置为“否”。

否则,如果您想要更多控制,请对 UILabel 所属的最顶层全屏 View (或窗口)进行子类化。

覆盖 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;

如果命中 View 不是您的 UILabel,则创建一个您在 UILabel 子类中处理的 NSNotification,然后取消选择。

顺便说一句,您也应该始终处理touchesCanceled!

关于iphone - 如何在 UILabel 上获取 "deselect"通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3891007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com