0

I am trying to fetch a list of users in a TableView, when my string contains "@". Only problem is, it keeps on observing users once the @ is in the text and doesn't stop, even when I have already selected a user and added that name to the text.. any idea, how to fix that? Here is my code:

    override func viewDidLoad() {
            super.viewDidLoad()
            
            NotificationCenter.default.addObserver(self, selector: #selector(checkUsername), name: UITextView.textDidChangeNotification, object: nil)  

 }

@objc func checkUsername() {
    
    if  (textView.text.range(of: "@" + "") != nil) {
        
        let range: Range<String.Index> = self.containerView.commentTextView.text.range(of: "@" + "")!
        
        self.textView.text.replaceSubrange(range, with: " ")
    
    }
    
}

let usernames = ["Ariana", "Brad", "Chelsea"]
JuFa512
  • 119
  • 7
  • I don't fully understand your question but I find it a bit strange that you find the range of string in one text view and then use that range to replace text in _another_ view. And what's up with `"@" + ""`, how is it different from `"@"`? – Joakim Danielson Jul 08 '22 at 09:09

1 Answers1

0

you could try using the addObserver(forName:object:queue:using:) variant.

Here are the docs: https://developer.apple.com/documentation/foundation/notificationcenter/1411723-addobserver

Then use, NotificationCenter.default.removeObserver(observer) when you want to remove the observation.

  • I have just tried this, but once i remove the observer, it will stop observing for good, even if there is another "@" in the textField ... – JuFa512 Jul 08 '22 at 09:39