|
| 1 | +// |
| 2 | +// TextViewController.swift |
| 3 | +// CodeEditTextViewExample |
| 4 | +// |
| 5 | +// Created by Khan Winter on 1/9/25. |
| 6 | +// |
| 7 | + |
| 8 | +import AppKit |
| 9 | +import CodeEditTextView |
| 10 | + |
| 11 | +class TextViewController: NSViewController { |
| 12 | + var scrollView: NSScrollView! |
| 13 | + var textView: TextView! |
| 14 | + |
| 15 | + init(string: String) { |
| 16 | + textView = TextView(string: string) |
| 17 | + super.init(nibName: nil, bundle: nil) |
| 18 | + } |
| 19 | + |
| 20 | + required init?(coder: NSCoder) { |
| 21 | + fatalError("init(coder:) has not been implemented") |
| 22 | + } |
| 23 | + |
| 24 | + override func loadView() { |
| 25 | + scrollView = NSScrollView() |
| 26 | + textView.translatesAutoresizingMaskIntoConstraints = false |
| 27 | + |
| 28 | + scrollView.translatesAutoresizingMaskIntoConstraints = false |
| 29 | + scrollView.documentView = textView |
| 30 | + scrollView.contentView.postsFrameChangedNotifications = true |
| 31 | + scrollView.contentView.postsBoundsChangedNotifications = true |
| 32 | + scrollView.hasVerticalScroller = true |
| 33 | + |
| 34 | + self.view = scrollView |
| 35 | + |
| 36 | + NSLayoutConstraint.activate([ |
| 37 | + scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), |
| 38 | + scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), |
| 39 | + scrollView.topAnchor.constraint(equalTo: view.topAnchor), |
| 40 | + scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor) |
| 41 | + ]) |
| 42 | + |
| 43 | + // Layout on scroll change |
| 44 | + NotificationCenter.default.addObserver( |
| 45 | + forName: NSView.frameDidChangeNotification, |
| 46 | + object: scrollView.contentView, |
| 47 | + queue: .main |
| 48 | + ) { [weak self] _ in |
| 49 | + self?.textView.updatedViewport(self?.scrollView.documentVisibleRect ?? .zero) |
| 50 | + } |
| 51 | + |
| 52 | + textView.updateFrameIfNeeded() |
| 53 | + } |
| 54 | + |
| 55 | + deinit { |
| 56 | + NotificationCenter.default.removeObserver(self) |
| 57 | + } |
| 58 | +} |
0 commit comments