@@ -5,6 +5,7 @@ import SwiftUI
5
5
class PostBodyCoordinator : NSObject , UITextViewDelegate , NSLayoutManagerDelegate {
6
6
@Binding var text : String
7
7
@Binding var isFirstResponder : Bool
8
+ @Binding var currentTextPosition : UITextRange ?
8
9
var lineSpacingMultiplier : CGFloat
9
10
var didBecomeFirstResponder : Bool = false
10
11
var postBodyTextView : PostBodyTextView
@@ -15,12 +16,14 @@ class PostBodyCoordinator: NSObject, UITextViewDelegate, NSLayoutManagerDelegate
15
16
_ textView: PostBodyTextView ,
16
17
text: Binding < String > ,
17
18
isFirstResponder: Binding < Bool > ,
19
+ currentTextPosition: Binding < UITextRange ? > ,
18
20
lineSpacingMultiplier: CGFloat
19
21
) {
20
22
self . postBodyTextView = textView
21
23
_text = text
22
24
_isFirstResponder = isFirstResponder
23
25
self . lineSpacingMultiplier = lineSpacingMultiplier
26
+ _currentTextPosition = currentTextPosition
24
27
}
25
28
26
29
func textViewDidChange( _ textView: UITextView ) {
@@ -29,6 +32,23 @@ class PostBodyCoordinator: NSObject, UITextViewDelegate, NSLayoutManagerDelegate
29
32
}
30
33
}
31
34
35
+ func textView( _ textView: UITextView , shouldChangeTextIn range: NSRange , replacementText text: String ) -> Bool {
36
+ self . currentTextPosition = textView. selectedTextRange
37
+ return true
38
+ }
39
+
40
+ func textViewDidBeginEditing( _ textView: UITextView ) {
41
+ if let textPosition = currentTextPosition {
42
+ textView. selectedTextRange = textPosition
43
+ }
44
+ }
45
+
46
+ func textViewDidEndEditing( _ textView: UITextView ) {
47
+ self . isFirstResponder = false
48
+ self . didBecomeFirstResponder = false
49
+ self . currentTextPosition = textView. selectedTextRange
50
+ }
51
+
32
52
func layoutManager(
33
53
_ layoutManager: NSLayoutManager ,
34
54
lineSpacingAfterGlyphAt glyphIndex: Int ,
@@ -55,6 +75,7 @@ struct PostBodyTextView: UIViewRepresentable {
55
75
@Binding var text : String
56
76
@Binding var textStyle : UIFont
57
77
@Binding var isFirstResponder : Bool
78
+ @Binding var currentTextPosition : UITextRange ?
58
79
@State var lineSpacing : CGFloat
59
80
60
81
func makeUIView( context: UIViewRepresentableContext < PostBodyTextView > ) -> UITextView {
@@ -82,6 +103,7 @@ struct PostBodyTextView: UIViewRepresentable {
82
103
self ,
83
104
text: $text,
84
105
isFirstResponder: $isFirstResponder,
106
+ currentTextPosition: $currentTextPosition,
85
107
lineSpacingMultiplier: lineSpacing
86
108
)
87
109
}
0 commit comments