我想在我的应用程序中使用Apple的Dictionary服务。测试代码如下。它可以得到单词的解释,问题是: 1,如何在func DCSGetTermRangeInString中获取偏移量,我在代码中设置为7 2.如何让文本视图响应键盘事件cmd + ctrl + d
//
// ContentView.swift
// testTextClick
//
// Created by lezi on 2020/6/2.
// Copyright © 2020 lezi. All rights reserved.
//
import SwiftUI
import Foundation
import AppKit
import CoreServices.DictionaryServices
struct ContentView: View {
let txt = "hello world"
var body: some View {
VStack{
Text(txt)
.contextMenu(){
Button("search xxx"){
let range = DCSGetTermRangeInString(nil, self.txt as CFString, 7)
let str = DCSCopyTextDefinition(nil,self.txt as CFString ,range)
print(str)
}
}
}
.frame(maxWidth:.infinity,maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
答案 0 :(得分:0)
NSTextView提供了更多的功能来完成这项工作。
override func mouseDown(with event: NSEvent) {
let location = event.locationInWindow
let point3 = self.window?.convertPoint(toScreen: location)
let idx = self.characterIndex(for: point3!)
let range = DCSGetTermRangeInString(nil, self.string as CFString, idx)
super.mouseDown(with: event)
}