Slide 46
Slide 46 text
import SwiftUI
@_spi(Advanced) import SwiftUIIntrospect
#if os(macOS)
import AppKit
public typealias TextView = NSTextView
public typealias TextViewDelegate = NSTextViewDelegate
#elseif os(iOS)
import UIKit
public typealias TextView = UITextView
public typealias TextViewDelegate = UITextViewDelegate
#endif
struct EditorView: View {
@State var text: String = ""
@Weak var textView: TextView? {
didSet {
textView?.delegate = delegate
}
}
var delegate = Delegate()
#if os(macOS)
final class Delegate: NSObject, TextViewDelegate {
func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
guard !textView.hasMarkedText() else {
return true
}
if replacementString == "\n" {
print("Enterが入力されたよ")
}
return true
}
}
#elseif os(iOS)
final class Delegate: NSObject, TextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard textView.markedTextRange == nil else {
return true
}
if text == "\n" {
print("Enterが入力されたよ")
}
return true
}
}
#endif
var body: some View {
TextEditor(text: $text)
#if os(macOS)
.introspect(.textEditor, on: .macOS(.v13, .v14)) { textView in
self.textView = textView
}
#elseif os(iOS)
.introspect(.textEditor, on: .iOS(.v16, .v17)) { textView in
self.textView = textView
}
#endif
}
}
#if os(macOS)
final class Delegate: NSObject, TextViewDelegate {
func textView(_ textView: NSTextView, shouldChangeTextIn
affectedCharRange: NSRange, replacementString: String?) -> Bool {
guard !textView.hasMarkedText() else {
return true
}
if replacementString == "\n" {
print("Enterが入力されたよ")
}
return true
}
}
#elseif os(iOS)
final class Delegate: NSObject, TextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange,
replacementText text: String) -> Bool {
guard textView.markedTextRange == nil else {
return true
}
if text == "\n" {
print("Enterが入力されたよ")
}
return true
}
}
#endif