Overview I'm building a simple project where I have a textView and a label. I want the label content to change every time the user copies a word from the textView and display it. At the moment I'm not able to do it automatically.
What I'm doing
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var refresh: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
label.text = UIPasteboard.general.string
refresh.addTarget(self, action: #selector(displayNew), for: .touchUpInside)
}
@objc func displayNew(){
label.text = UIPasteboard.general.string
}
}
So whenever the user presses the refresh button the label's text refreshes. Now I need it to happen automatically.
Question
How would ypu refresh the label's text automatically whenever the user copies something?
Add a listener
NotificationCenter.default.addObserver(self, selector: #selector(clipChange),
name: UIPasteboard.changedNotification, object: nil)
@objc func clipChange(){
label.text = UIPasteboard.general.string
}