swift - 选择更改时,通过 NSViewRepresentable 将值从 NSTextView 传递到父 SwiftUI 视图
问题描述
问题
我希望能够从 textView.textStorage 的选定范围和/或 textView 的键入属性传递文本属性。这应该在选择更改时发生。
这样做的目的是让 SwiftUI 视图可以根据用户使用的属性进行更新。
我正在尝试使用该textViewDidChangeSelection
方法来做到这一点。但是,使用 NSTextViewDelegate 我只能获得选定的范围,并且不能传递从 textView 中存储的任何值。
我的尝试
下面是我的 RepresentableView 的精简版。
import SwiftUI
struct TextViewMacOS: NSViewRepresentable {
@Binding var currentTypingAttributes: [NSAttributedString.Key : Any]
@Binding var currentTextAttributes: [NSAttributedString.Key : Any]
class Coordinator: NSObject, NSTextViewDelegate {
var parent: TextViewMacOS
init(_ parent: TextViewMacOS) {
self.parent = parent
}
func textViewDidChangeSelection(_ notification: Notification) {
/*
// Trying to do something like below:
// parent.currentTypingAttributes = textView.typingAttributes
// parent.currentTextAttributes = textView.textStorage?.attributes(at: textView.selectedRange().lowerBound, effectiveRange: nil)
*/
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
public func makeNSView(context: Context) -> NSTextView {
//[...]
}
public func updateNSView(_ textView: NSTextView, context: Context) {
//[...]
}
}
是否可以创建订阅相同通知但传递 textView 的自定义方法?我必须制作自定义代表吗?
任何帮助将不胜感激。干杯。
解决方案
推荐阅读
- c++ - 如何覆盖先前的数组值
- apache-kafka - 尝试安装 MQTT 连接器(源和接收器)时出错
- reactjs - 在本地部署 React App - localhost 拒绝连接
- drupal-console - console.site_install - 您请求了一个不存在的服务“extension.list.module”。在 Drupal 控制台中
- .net-core - .net 核心包和对 .net 运行时的依赖
- ionic-framework - Agora Video Sdk 本地视频不可见 只有连接的客户端视频可见 没有两种方式可见
- python - Python双重导入奇怪的行为
- google-chrome-devtools - 检查 firefox devtools 扩展
- flutter - 使用 Flutter 2.0 / Dart 12 在 flutter_openvpn 中构建 win32 插件错误
- microsoft-graph-api - 读取 MS Graph 中的所有组需要什么权限