Reputation: 25
i'm trying to make it so that every time i press enter in a textfield
it makes a NSTextView automaticly scroll down to the last line in the scrollview
let range = NSMakeRange(textView.text.characters.count - 1, 0)
textView.scrollRangeToVisible(range)
i tried all sort of ways but it never scroll down the text in the NSTextView
Upvotes: 1
Views: 190
Reputation: 236360
You can addLocalMonitorForEvents
for .keyDown
events to your view controller and check if the event.keyCode == 76
.
import Cocoa
class ViewController: NSViewController {
@IBOutlet var textview: NSTextView!
var keyDown: Any!
override func viewDidLoad() {
super.viewDidLoad()
keyDown = NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
self.keyDown(with: $0)
return $0
}
}
override func keyDown(with event: NSEvent) {
if event.keyCode == 76 {
print("enter key pressed")
DispatchQueue.main.async {
self.textview.scrollRangeToVisible(NSRange(location: self.textview.string.count, length: 0))
}
}
}
deinit {
NSEvent.removeMonitor(keyDown)
}
}
If you just need to scroll it down after your method adds lines to the textview just add this to the end of it:
DispatchQueue.main.async {
self.textview.scrollRangeToVisible(NSRange(location: self.textview.string.count, length: 0))
}
Upvotes: 1