防止编辑UITextField中的文本,并在使用inputView时隐藏光标/插入/放大镜
我如何防止编辑UITextField
的文本,同时隐藏光标/插入/放大镜,但仍然显示键盘,因为我正在使用UIPickerView
/ UIDatePickerView
的inputView
?
将userInteractionEnabled
设置为NO
不起作用,因为它不再接收任何触摸,并且不会显示键盘。
子类UITextField
//Disables caret - (CGRect)caretRectForPosition:(UITextPosition *)position { return CGRectZero; } //Disables magnifying glass -(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer { if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) { gestureRecognizer.enabled = NO; } [super addGestureRecognizer:gestureRecognizer]; }
在你的UITextFieldDelegate
//Prevent text from being copied and pasted or edited with bluetooth keyboard. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { return NO; }
现在只需从你的UIPickerView / UIDatePicker的结果编程设置你的文本。
在iOS 7中隐藏光标要简单得多。仍然需要一些技巧来禁用放大镜
textField.tintColor = [UIColor clearColor];
我希望这会对你有所帮助。
设置光标UIColor – >空白。 在UI中,它将被隐藏。
[[self.textField valueForKey:@"textInputTraits"] setValue:[UIColor clearColor] forKey:@"insertionPointColor"];
我发现最好的解决scheme是
- (CGRect) caretRectForPosition:(UITextPosition*) position { return CGRectZero; } - (NSArray *)selectionRectsForRange:(UITextRange *)range { return nil; } - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == @selector(copy:) || action == @selector(selectAll:) || action == @selector(paste:)) { returnNO; } return [super canPerformAction:action withSender:sender]; }
http://b2cloud.com.au/tutorial/disabling-the-caret-and-text-entry-in-uitextfields/
有一个没有交互的UITextField
,但仍然使用inputView
:
具有以下方法的子类UITextField:
// Hide the cursor - (CGRect)caretRectForPosition:(UITextPosition*)position { return CGRectZero; } // All touches inside will be ignored // and intercepted by the superview - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { return NO; }
最后的方法将单独防止任何编辑和放大镜玻璃,因为你将无法点击UITextField
。
例如,如果您在UITableViewCell
使用文本字段,则此function非常有用,然后可以通过tableView:didSelectRowAtIndexPath:
切换firstResponder状态。
要禁用任何与文本字段的交互,除了使其成为第一响应者,您可以将相同大小的UIButton放在文本字段的正上方。 button点击事件的代码可能是这样的:
- (IBAction)btnEditPhoneTapped:(id)sender { if (self.tfClientPhoneNo.isFirstResponder == NO) [self.tfClientPhoneNo becomeFirstResponder]; }