Issue #730
Use NSTextField
with maximumNumberOfLines
import AppKit
import SwiftUI
struct AttributedText: NSViewRepresentable {
let attributedString: NSAttributedString
init(_ attributedString: NSAttributedString) {
self.attributedString = attributedString
}
func makeNSView(context: Context) -> NSTextField {
let textField = NSTextField()
textField.lineBreakMode = .byClipping
textField.maximumNumberOfLines = 0
textField.isBordered = false
return textField
}
func updateNSView(_ nsView: NSTextField, context: Context) {
nsView.attributedStringValue = attributedString
}
}
TextField has problem with wrapping, we can use TextView
struct AttributedTextView: NSViewRepresentable {
typealias NSViewType = NSScrollView
let attributedText: NSAttributedString?
let isSelectable: Bool
var insetSize: CGSize = .zero
func makeNSView(context: Context) -> NSViewType {
let scrollView = NSTextView.scrollableTextView()
let textView = scrollView.documentView as! NSTextView
textView.drawsBackground = false
textView.textColor = .controlTextColor
textView.textContainerInset = insetSize
return scrollView
}
func updateNSView(_ nsView: NSViewType, context: Context) {
let textView = (nsView.documentView as! NSTextView)
textView.isSelectable = isSelectable
if let attributedText = attributedText,
attributedText != textView.attributedString() {
textView.textStorage?.setAttributedString(attributedText)
}
if let lineLimit = context.environment.lineLimit {
textView.textContainer?.maximumNumberOfLines = lineLimit
}
}
}