0

我正在尝试创建一个类,该类创建一个允许用户复制其内容的只读文本字段。这是我的代码:

CopyOnly.h

#import <UIKit/UIKit.h>

@interface CopyOnly : UITextField

@end

CopyOnly.m

#import "CopyOnly.h"

@implementation CopyOnly

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self attachTapHandler];
    }
    return self;
}

- (void) attachTapHandler
{
    [self setUserInteractionEnabled:YES];
    UIGestureRecognizer *touchy = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self addGestureRecognizer:touchy];
}

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

- (void) handleTap: (UIGestureRecognizer*) recognizer
{
    [self becomeFirstResponder];
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setTargetRect:self.frame inView:self.superview];
    [menu setMenuVisible:YES animated:YES];
}

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

- (BOOL) canBecomeFirstResponder
{
    return YES;
}

@end

这很好用,只有键盘出现了。我不想出现任何键盘。

我尝试将此添加到initWithFrame:

UIView* noKeyboard = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
self.inputView = noKeyboard;

这并没有给我我期望的结果。有谁知道我该怎么做?

4

3 回答 3

2

扩展我的评论。这很容易使用属性设置为的UITextView(not UITextField)来完成。editableNO

UITextView* tf = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 50)];
tf.editable = NO;
tf.text = @"Hey this is a test!";
[self.view addSubview:tf];

在此处输入图像描述

于 2014-04-25T14:00:43.333 回答
0

将此添加到 -(BOOL)canBecomeFirtResponder 似乎可以解决问题。哈克,但它的工作原理。

- (BOOL) canBecomeFirstResponder
{
    UIView* noKeyboard = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    self.inputView = noKeyboard;
    return YES;
}
于 2014-04-25T13:49:56.510 回答
0

如果您坚持使用不允许编辑的文本字段,请尝试完全不同的方法。按照本文http://nshipster.com/uimenucontroller/中的说明实现支持复制的 UILabel。

于 2014-04-25T14:01:15.540 回答