1

I am trying to implement a button to trigger the original text I have in the UItextView. I have looked at this post: Trigger button to change text in UITextView in swift3 xcode 8 ios 10

and followed it I realized it only worked for UItextField. Since I need to wrap the my text, I am wondering is that possible to do the similar action with UItextView?

Currently, I have:

@IBOutlet var Textfield: UITextView!
@IBOutlet var ChangingText: [UIButton]!


@IBAction func ChangingTextTapped(_ sender: Any) {
        Textfield.text = "Changing text here"
    }

But I got the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM setText:]: unrecognized selector sent to instance 0x282d15b90'

Thanks in advance!

Solution: It works well following the suggestion from Dejan Atanasov:

 @IBOutlet var Textfield: UITextView!
    @IBOutlet var ChangingText: UIButton!


    @IBAction func ChangingTextTapped(_ btn: UIbutton) {
            Textfield.text = "Changing text here"
        }`
swiftlearneer
  • 324
  • 4
  • 17

3 Answers3

3

For changing the UITextView text by pressing on a button you will need the following code:

@IBOutlet fileprivate weak var textView: UITextView!
@IBOutlet fileprivate weak var changeTextBtn: UIButton!


@IBAction func onChangeTextButton(_ btn: UIButton){
    textView.text = "Change text to something else!"
}

Connect the @IBAction with the button in the Interface Builder and make sure you select the Touch Up Inside event (see screenshot). That's it!

enter image description here

This is the result when I click on the button:

enter image description here

Dejan Atanasov
  • 1,202
  • 10
  • 13
  • It works very well! Thank you! I think changing _btn: UIbutton is the key! – swiftlearneer Jun 07 '20 at 20:20
  • Could I can ask you a follow up question? If I have multiple text line that I want to change using the same button, could I add more lines of textView.text = "Change1!", textView.text = "Change2!" like this? Would it be possible? – swiftlearneer Jun 07 '20 at 20:22
  • No, you can't call textVew.text twice, it will just overwrite the previous value. If you want to add text in a new line, you should use textView.text = "Change1!\nChange2!". – Dejan Atanasov Jun 08 '20 at 05:50
1

No need to add array of buttons.

@IBOutlet weak var textViewDemo: UITextView!

@IBAction func upgradeBtnTapped(_ sender: Any) {

textViewDemo.text = "Set Something else"
}
Jaykant
  • 349
  • 4
  • 11
0

The Issue with your code was the following line:

@IBOutlet var ChangingText: [UIButton]!

Your have declared your button as an array of UIButtons by enclosing UIButton in Brackets...[UIButton]. Simply remove the brackets.

Martin Muldoon
  • 3,388
  • 4
  • 24
  • 55