Skip to content

Instantly share code, notes, and snippets.

@jranson
Created December 21, 2020 19:12
Show Gist options
  • Save jranson/35ec23f0d6f87bc179b30024928f4668 to your computer and use it in GitHub Desktop.
Save jranson/35ec23f0d6f87bc179b30024928f4668 to your computer and use it in GitHub Desktop.
TextView control for SwiftUI
//
// TextView.swift
// TextView provides a scrollable, read-only, clipboard-copyable text field
// for use with SwiftUI macOS apps. Because it uses NS* classes, it is
// not compatible with iOS, tvOS, etc.
//
// Created by James Ranson on 12/19/20.
//
import Foundation
import SwiftUI
struct TextView: NSViewRepresentable {
@Binding var text: String
let scrollView: NSScrollView = NSTextView.scrollableTextView()
init(text: Binding<String>) {
self._text = text
}
func makeNSView(context: Context) -> NSScrollView {
let textView = scrollView.documentView as! NSTextView
textView.isSelectable = true
textView.isVerticallyResizable = true
textView.isHorizontallyResizable = false
textView.isRichText = false
textView.importsGraphics = false
textView.isEditable = false
textView.drawsBackground = false
textView.autoresizingMask = [.width]
scrollView.hasVerticalScroller = true
scrollView.drawsBackground = false
return scrollView
}
func updateNSView(_ uiView: NSScrollView, context: Context) {
let tv = uiView.documentView as! NSTextView
tv.string = text
tv.scrollToEndOfDocument(nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment