我正在尝试创建一个类,该类创建一个允许用户复制其内容的只读文本字段。这是我的代码:
只复制.h
#import <UIKit/UIKit.h>
@interface CopyOnly : UITextField
@end
只复制.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;
这并没有给我预期的结果。有人知道我该怎么做吗?
最佳答案
扩展我的评论。使用 UITextView
(不是 UITextField
)并将 editable
属性设置为 NO
可以轻松实现这一点。
UITextView* tf = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 50)];
tf.editable = NO;
tf.text = @"Hey this is a test!";
[self.view addSubview:tf];
关于ios - Objective C 子类 UITextField 只复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23294693/