7

我承认在 SO 上已经有一个完全符合这些思路的问题,但它缺乏实现细节,一个有效的答案,我想更具体一些,所以我认为一个新问题是有序的。显然,如果我错了,请告诉我,我们可以尝试重新启动那里的线程

基本上,当用户按住标签时,我想将 UILabel 中的文本复制到粘贴板。老实说,不难做到。但是,我认为提供视觉反馈的最佳方式是使用复制菜单选项来提示用户UIMenuController

根据 iPhone 应用程序编程指南的事件处理部分,特别是关于复制、剪切和粘贴操作的部分,应该可以从自定义视图中提供复制、剪切和/或粘贴操作。

因此,我已经按照指南中的描述使用以下实现对 UILabel 进行了子类化,但 UIMenuController 不会出现。指南中没有任何迹象表明需要执行此操作,并且 NSLog 语句确实打印到控制台,表明当我按住标签时正在执行选择器:

//
//  CopyLabel.m
//  HoldEm
//
//  Created by Billy Gray on 1/20/10.
//  Copyright 2010 Zetetic LLC. All rights reserved.
//

#import "CopyLabel.h"

@implementation CopyLabel

- (void)showCopyMenu {
    NSLog(@"I'm tryin' Ringo, I'm tryin' reeeeal hard.");
    // bring up editing menu.
    UIMenuController *theMenu = [UIMenuController sharedMenuController];
    // do i even need to show a selection? There's really no point for my implementation...
    // doing it any way to see if it helps the "not showing up" problem...
    CGRect selectionRect = [self frame];
    [theMenu setTargetRect:selectionRect inView:self];
    [theMenu setMenuVisible:YES animated:YES]; // <-- doesn't show up...
}

// obviously, important to provide this, but whether it's here or not doesn't seem
// to change the fact that the UIMenuController view is not showing up
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    BOOL answer = NO;

    if (action == @selector(copy:))
        answer = YES;

    return answer;
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self performSelector:@selector(showCopyMenu) withObject:nil afterDelay:0.8f];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showCopyMenu) object:nil];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showCopyMenu) object:nil];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showCopyMenu) object:nil];
}

@end

那么,要实现这一目标,还需要做什么呢?

对于那些跟随并尝试这样做的人,您还需要为标签设置“启用用户交互”

编辑:

为了清楚起见,让我补充一点,当您按住它时,这应该类似于在某些 iphone 视图中出现在图像上的小 [复制] 菜单项。-B

4

1 回答 1

7

我会提前说我没有答案,但我做了一些探索并发现了更多信息。我确定您已经看过这个:CopyPasteTile

该代码确实可以在我的模拟器上运行,并且如下所示:

CGRect drawRect = [self rectFromOrigin:currentSelection inset:TILE_INSET];
[self setNeedsDisplayInRect:drawRect];

UIMenuController *theMenu = [UIMenuController sharedMenuController];
[theMenu setTargetRect:drawRect inView:self];
[theMenu setMenuVisible:YES animated:YES];

这里有一些区别:

  • drawRect 是从一个巨大的视图瓦片和点击点计算中计算出来的
  • setNeedsDisplayInRect被调用
  • self是一个大屏幕尺寸的视图,您可能需要屏幕坐标而不是本地坐标(您可能可以从 self.superview 获得)

我会先尝试进行这些调整以匹配示例,然后看看它给我带来了什么样的进步。

于 2010-01-21T16:51:13.133 回答