Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear previous text in UITextView before writing text?

Tags:

iphone

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.

like image 461
user698200 Avatar asked Sep 10 '11 14:09

user698200


People also ask

What is UITextView used for?

UITextView supports the display of text using custom style information and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document.

How do I display multiple text styles in UITextView?

UITextView supports the display of text using custom style information and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document. This class supports multiple text styles through use of the attributedText property.

How do I remove the keyboard from a text view?

To dismiss the keyboard, send the resignFirstResponder () message to the text view that is currently the first responder. Doing so causes the text view object to end the current editing session (with the delegate object’s consent) and hide the keyboard.


2 Answers

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:@""];
}
like image 142
max_ Avatar answered Oct 02 '22 15:10

max_


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

like image 33
Hardik Thakkar Avatar answered Oct 02 '22 14:10

Hardik Thakkar