创建滚动视图
文本视图不会滚动的原因是 Mac 文本视图不像 iOS 文本视图那样包含在滚动视图中。创建文本视图时,必须同时创建文本视图和滚动视图。将滚动视图的文档视图设置为文本视图。给滚动视图一个垂直滚动条。返回滚动视图。
func makeNSView(context: Context) -> NSScrollView {
let textView = NSTextView()
textView.autoresizingMask = [.width, .height]
textView.isEditable = true
textView.delegate = context.coordinator
textView.allowsUndo = true
let scrollView = NSScrollView()
scrollView.hasVerticalScroller = true
scrollView.documentView = textView
return scrollView
}
设置自动调整大小掩码可确保文本视图在窗口调整大小时正确调整大小。
更新视图
编写updateNSView函数时,提供滚动视图作为参数。使用documentView滚动视图的属性访问文本视图并更新其内容。
func updateNSView(_ scrollView: NSScrollView, context: Context) {
guard let textView = scrollView.documentView
as? NSTextView else {
assertionFailure("unexpected text view")
return
}
if textView.delegate !== context.coordinator {
textView.delegate = context.coordinator
}
// model is your data model whose text you are
// showing and editing in the text view.
textView.string = model.text
}
精品教程推荐
加入我们一起学习SwiftUI
QQ:3365059189
SwiftUI技术交流QQ群:518696470
教程网站:www.openswiftui.com