不可编辑的UITextField带有复制菜单

8
有没有一种方法可以使UITextField不能被用户编辑,并且只提供复制菜单而不用子类化?即当触摸文本字段时,它会自动选择所有文本并仅显示复制菜单。
如果可能在不使用子类化的情况下完成此操作,那么需要选择哪些界面构建器选项?
谢谢。
5个回答

5

只需执行以下操作:

(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return NO;
}

同时还有:

yourTextField.inputView = [[UIView alloc] init];

4

1
好的,我在最初的搜索中就遇到了这个条目。因此看起来你不能不使用子类化来完成它。 - cubiclewar
@ TDawg:你可以使用我提供的链接。 - Jhaliya - Praveen Sharma

0

不使用子类化,但也不使用自动选择,即用户可以选择,键盘会弹出,但用户无法输入数据:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return NO;
}

0

制作一个UITextField所需的项目(在此案例中,outputTextField), 使其能够接受触摸并允许选择、全选、复制、粘贴, 但不可编辑区域,并禁用弹出键盘:

  1. 在 @interface 中 ViewController 声明后面的尖括号中加入 "UITextFieldDelegate"
  2. -(void)viewDidLoad{} 方法中添加以下两行:

     self.outputTextField.delegate = self;
    
     self.outputTextField.inputView = [[UIView alloc] init];
    
  3. 添加委托方法(见下方实际方法):

    textField: shouldChangeCharactersInRange:replacementString: { }
    
//  ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController 
@end


// ViewController.m
#import "ViewController.h"

@interface ViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *inputTextField;
@property (weak, nonatomic) IBOutlet UITextField *outputTextField;
- (IBAction)copyButton:(UIButton *)sender;
@end

@implementation ViewController
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range

replacementString:(NSString *)string
{

    NSLog(@"inside shouldChangeCharactersInRange");

    if (textField == _outputTextField)
    {
        [_outputTextField resignFirstResponder];     
    }
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.outputTextField.delegate = self; // delegate methods won't be called without this
    self.outputTextField.inputView = [[UIView alloc] init]; // UIView replaces keyboard
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)copyButton:(UIButton *)sender {
    self.outputTextField.text = self.inputTextField.text;
    [_inputTextField resignFirstResponder];
    [_outputTextField resignFirstResponder];
}
@end

0

这对我很有用,使UITextField不可编辑,只允许复制。只需将您的UITextField类从XIB更改为CopyAbleTF即可。

@implementation CopyAbleTF

- (void)awakeFromNib{


    self.inputView= [[UIView alloc] init];

}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{

    if (action == @selector(copy:))
    {
        return true;
    }

    return false;
}



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



@end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接