有没有一种方法可以使UITextField不能被用户编辑,并且只提供复制菜单而不用子类化?即当触摸文本字段时,它会自动选择所有文本并仅显示复制菜单。
如果可能在不使用子类化的情况下完成此操作,那么需要选择哪些界面构建器选项?
谢谢。
如果可能在不使用子类化的情况下完成此操作,那么需要选择哪些界面构建器选项?
谢谢。
只需执行以下操作:
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return NO;
}
同时还有:
yourTextField.inputView = [[UIView alloc] init];
UITextField
的 enabled
属性设置为 NO
来禁用编辑。textField.enabled = NO;
不使用子类化,但也不使用自动选择,即用户可以选择,键盘会弹出,但用户无法输入数据:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return NO;
}
制作一个UITextField
所需的项目(在此案例中,outputTextField),
使其能够接受触摸并允许选择、全选、复制、粘贴,
但不可编辑区域,并禁用弹出键盘:
在 -(void)viewDidLoad{}
方法中添加以下两行:
self.outputTextField.delegate = self;
self.outputTextField.inputView = [[UIView alloc] init];
添加委托方法(见下方实际方法):
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
这对我很有用,使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