简体   繁体   中英

Swift: a button to change the text in the UItextView?

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"
        }`

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!

在此处输入图像描述

This is the result when I click on the button:

在此处输入图像描述

No need to add array of buttons.

@IBOutlet weak var textViewDemo: UITextView!

@IBAction func upgradeBtnTapped(_ sender: Any) {

textViewDemo.text = "Set Something else"
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM