Uitextview Data Change Swift

UITextView data change swift

You need to set UITextView delegate and implement textViewDidChange: method in it. Unfortunately, I do not know if swift documentation is available online. All the links go to the objective-c documentation.

The code will look like this: (updated for SWIFT 4.2)

class ViewController: UIViewController, UITextViewDelegate { //If your class is not conforms to the UITextViewDelegate protocol you will not be able to set it as delegate to UITextView

@IBOutlet weak var bodyText: UITextView!

override func viewDidLoad() {
super.viewDidLoad()
bodyText.delegate = self //Without setting the delegate you won't be able to track UITextView events
}

func textViewDidChange(_ textView: UITextView) { //Handle the text changes here
print(textView.text); //the textView parameter is the textView where text was changed
}
}

Detect when a UITextView has been edited

To do this, you need to conform to the UITextViewDelegate protocol and then set the textView's delegate to self.

So, after UIViewController on the beginning of this view controller, you need to add the protocol conformance. Example

class MyViewController: UIViewController, UITextViewDelegate {

then set the delegate in viewDidLoad():

override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}

Now, you're set up for success. All of the delegate methods on UITextViewDelegate are optional, so you only need to implement the ones you want. In this case, the one you want to implement is func textViewDidChange(_ textView: UITextView)

That method will get triggered every single time the text in the text field updates.

text changed event in UITextView

You need to set the delegate inside viewDidLoad

textView.delegate = self

//

class ViewController: UIViewController , UITextViewDelegate  {

How to change a variable UITextView after clicking the button?

On click of button, create a new texView and assign it a tag value. Once it is added, update the value of i to +1, so that every textView added has a new tag value.

var i = 1
var newText = UITextView()

@IBAction func addTextButton(_ sender: Any) {

newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
self.StoriesView.addSubview(newText)

newText.font = UIFont(name: "Verdana", size: 11)
newText.text = "TAP TO EDIT #\(i)"
newText.sizeToFit()
newText.textColor = UIColor.black
newText.backgroundColor = UIColor.clear
newText.tag = i

newText.isEditable = true
newText.isSelectable = true
newText.isUserInteractionEnabled = true
newText.allowsEditingTextAttributes = true
newText.translatesAutoresizingMaskIntoConstraints = true

newText.enablesReturnKeyAutomatically = true

newText.delegate = self
//increment i
i+=1
}

then you can access your textField via tag values like this:

if let textView = self.StoriesView.viewWithTag(i) as? UITextView {
// textView.text = "change it"
}

UPDATE:

Add textView Delegate method, and once a textView starts editing, change the newText value to the currently editing textView

class ViewController : UIViewController, UITextViewDelegate {

func textViewDidBeginEditing(_ textView: UITextView) {
newText = textView
}
}

How to respond to programmatic changes of a TextView text

I just tried KVO on UITextView,

 self.textView1.text = "You are working, but I will change you in 5 seconds"

Add your observer

self.textView1.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)

Trigger text change programmatically, just an example do it the way you want.

 DispatchQueue.main.asyncAfter(deadline:.now() + 5) {
self.textView1.text = "Changed after some time"
}

Override the KVO method.

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object == self.textView1{
//do your thing here...
}
}

FYI from Apple docs below

Note: Although the classes of the UIKit framework generally do not
support KVO, you can still implement it in the custom objects of your
application, including custom views.

https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/KVO.html

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

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!

Sample Image

This is the result when I click on the button:

Sample Image

UITextView observe text changes

OK, after a lot of research I've tried RxSwift because I thought that observing text in reactive paradigm framework should succeed in 100% cases. And it worked without any issues!

inputTextView.rx.text.subscribe(onNext: { string in
print("rx: \(string)")
})

So it seems that these guys have found the solution.

https://github.com/ReactiveX/RxSwift/blob/master/RxCocoa/iOS/UITextView%2BRx.swift

And here is the solution that gives you information about all text changes despite of auto correction, text selection, and etc..

class ViewController: UIViewController {

@IBOutlet weak var inputTextView: UITextView!

override func viewDidLoad() {
super.viewDidLoad()
inputTextView.textStorage.delegate = self
}
}

extension ViewController: NSTextStorageDelegate {
func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int) {
print("string: \(textStorage.string)")
}
}

Track text change in UITextview when not entered through keyboard

You can try below Swift 3 code:-

@IBAction func buttonClicked(sender: AnyObject) {
self.textView.text = self.textView.text + "AA" //suppose you are trying to append "AA" on button click which would call the below delegate automatically
}

//Below delegate of UITextViewDelegate will be called from keyboard as well as in button click
func textViewDidChangeSelection(_ textView: UITextView) {
if textView.text.characters.count > 100 {

let tempStr = textView.text
let index = tempStr?.index((tempStr?.endIndex)!, offsetBy: 100 - (tempStr?.characters.count)!)
textView.text = tempStr?.substring(to: index!)
}
}

Saving data in UITextView

There are two subtasks to saving the data: updating the Core Data entity with the contents of the text view and saving the Core Data context.

To update the contents of the Core Data entity, add a function to the AddEditNotes class that saves the text view contents.

func saveTextViewContents() {
note.text = textView.text
// Add any other code you need to store the note.
}

Call this function either when the text view ends editing or the text changes. If you call this function when the text changes, the Core Data entity will always be up to date. You won't have to pass the data to the app delegate because the app delegate has the Core Data managed object context.

To save the Core Data context, add a second function to the AddEditNotes class that saves the context.

func save() {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.saveContext()
}
}

This function assumes you selected the Use Core Data checkbox when you created the project. If you did, the app delegate has a saveContext function that performs the Core Data save.

You can now replace the code you wrote in viewWillDisappear with the calls to the two functions to save the text view contents and save the context.

The last code to write is to go to your app delegate file and add the following line of code to the applicationDidEnterBackground and applicationWillTerminate functions:

self.saveContext()

By adding this code your data will save when someone quits your app.



Related Topics



Leave a reply



Submit