Search code examples
iosuitextviewuitextfielddelegate

How to programmatically enter text into a UITextView by Clicking a Button using Swift


I have a UITextView and Two UIButtons ( ButtonOne and ButtonTwo). I would like to type text into this UITextView by clicking ButtonOne and ButtonTwo.

For example, if I click ButtonOne it should type “apple” into the UITextView and after this if I click ButtonTwo it should type “orange” into the UITextView. So after I have clicked these two buttons one after another I should have the following text in my UITextView:

apple orange

I can actually do this currently by using the following line of code:

myTextView.text = myTextView.text.stringByAppendingString("orange ")

However the problem is that when after type some text into myTextView if I then manually enter some text into myTextView (using the keyboard) and then click ButtonOne (or ButtonTwo) again, all the manually entered text gets removed from myTextView and I am only left wit the text entered by clicking buttons.

I would like to be able to enter text both by clicking buttons as well as by typing using keyboard interchangeably.

I can do this kind of thing very easily using a RichTextBox control in .NET application. So a related question I have in this connection is what is the equivalent of a .NET RichTextBox control in iOS.


Solution

  • try with following code.

    @IBOutlet weak var yourTextView: UITextView!
    
        @IBAction func appleTap(sender: AnyObject) {
            yourTextView.text = yourTextView.text .stringByAppendingString("Apple ")
        }
    
        @IBAction func OrangeTap(sender: AnyObject) {
            yourTextView.text = yourTextView.text .stringByAppendingString("Orange ")
        }
    

    Above code is worked for me if you still having problem then please write your code in question.