0

I'm trying to create a class that makes a read only text field that allows the user to copy its contents. Here is my code:

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

This works great, only the keyboard is coming up. I don't want any keyboard to come up.

I tried adding this to initWithFrame:

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

This does not give me the result I'm expecting. Anyone know how I can do this?

Jared Price
  • 5,217
  • 7
  • 44
  • 74

3 Answers3

2

Extending on my comment. This is easily accomplished using a UITextView (not UITextField) with editable property set to 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];

enter image description here

Odrakir
  • 4,254
  • 1
  • 20
  • 52
0

Adding this to -(BOOL)canBecomeFirtResponder seemed to do the trick. Hacky, but it works.

- (BOOL) canBecomeFirstResponder
{
    UIView* noKeyboard = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    self.inputView = noKeyboard;
    return YES;
}
Jared Price
  • 5,217
  • 7
  • 44
  • 74
0

If you stuck with text field that doesn't allow editing try totally different approach. Follow instructions in this article http://nshipster.com/uimenucontroller/ to implement UILabel that supports copying.

user2260054
  • 522
  • 1
  • 3
  • 11