How to clear previous text in UITextView before writing text?
I want to clear previous text written on UITextView before new text is written on it. I did like this.
textView.text = @"";
textView.text = @"something";
But, previous text is not cleared. It overlaps with current text. Textview开发者_StackOverflow社区 is non-editable.
You need to implement the UITextViewDelegate and the method, textViewDidBeginEditing
. The following code sets the textView's text to @""
(nothing) when it starts editing.
- (void) textViewDidBeginEditing:(UITextView *) textView {
[textView setText:@""];
}
Here is a code for swift
func textViewDidBeginEditing(textView: UITextView) {
txtView.text = ""
txtView.textColor = UIColor.blackColor()
}
func textViewDidEndEditing(textView: UITextView) {
if txtView.text.isEmpty {
txtView.text = "Write your comment."
txtView.textColor = UIColor.blackColor()
}
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n" // Recognizes enter key in keyboard
{
textView.resignFirstResponder()
return false
}
return true
}
Note : give delegate to your textview
Set the selected range to the entire text of the textView first:
[textView setSelectedRange:NSMakeRange(0, textView.text.length)];
[textView setText:@""];
As in:
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
// Make the textView visible in-case the keyboard has covered it
[table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
// Keyboard toolbar prev/next buttons
[nextPreviousControl setEnabled:YES forSegmentAtIndex:0];
[nextPreviousControl setEnabled:NO forSegmentAtIndex:1];
//
// Erase all text in the textView before editing starts:
//
[textView setSelectedRange:NSMakeRange(0, textView.text.length)];
[textView setText:@""];
return YES;
}
Set the clearsOnBeginEditing for your text field.
精彩评论