本文价值与收获
看完本文后,您将能够作出下面的界面
看完本文您将掌握的技能
- NSTextField基础使用
- SwiftUI调用macOS
代码
import SwiftUI
struct ContentView: View {
@State var text = ""
var body: some View {
VStack{
Text("SwiftUI text")
Group{
TextField("请输入", text: self.$text)
.padding()
MyTextField(text: self.$text)
.padding()
}.frame(width:200)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
import AppKit
struct MyTextField: NSViewRepresentable {
@Binding var text: String
func makeNSView(context: NSViewRepresentableContext<MyTextField>) -> NSTextField {
let tf = NSTextField()
tf.focusRingType = .none
tf.isBordered = false
tf.drawsBackground = true
tf.delegate = context.coordinator
return tf
}
func updateNSView(_ nsView: NSTextField, context: NSViewRepresentableContext<MyTextField>) {
nsView.stringValue = text
}
func makeCoordinator() -> MyTextField.Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, NSTextFieldDelegate {
let parent: MyTextField
init(parent: MyTextField) {
self.parent = parent
}
func controlTextDidChange(_ obj: Notification) {
let textField = obj.object as! NSTextField
parent.text = textField.stringValue
}
}
}
技术交流
QQ:3365059189
SwiftUI技术交流QQ群:518696470