Reputation: 399
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 is non-editable.
Upvotes: 8
Views: 13127
Reputation: 25
Just call your TextView and clear the string before you insert your own string.
textView.text.removeAll(keepingCapacity: false)
This line of code will remove the string in the text view. I just used this to clear a textView prior to repopulating with updated data from a databse.
Upvotes: 0
Reputation: 15951
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
Upvotes: 3
Reputation: 52738
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;
}
Upvotes: 2
Reputation: 24481
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:@""];
}
Upvotes: 9