-
Notifications
You must be signed in to change notification settings - Fork 0
[#292] TodoEditorView에서 content의 상단 부분을 수정하려고 시도하면 키보드가 내려간 상태에서 누르면 무조건 아래쪽으로 내려가는 이슈를 해결한다 #298
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7de0d9f
feat: UIKitTextEditor 구현 및 사용 (데모)
opficdev 1712c66
feat: 폰트 관리 일원화 및 최소 높이를 해당 폰트의 lineHeight로 조정
opficdev 4f29a80
fix: TextEditor 자체를 탭 했을 때 한글자 입력 후 포커싱이 해제되는 현상 해결
opficdev 45eb335
ui: 기본 폰트 body로 수정
opficdev 952d7b1
refactor: .focused() 모디파이어로 포커싱 제어
opficdev b5eae9f
fix: Main actor-isolated property 'logger' can not be referenced from…
opficdev 9f94bb6
refactor: DispatchQueue보다 안정적으로 KVO 패턴을 채택하여 개선
opficdev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -323,9 +323,6 @@ | |
| }, | ||
| "생성일" : { | ||
|
|
||
| }, | ||
| "설명(선택)" : { | ||
|
|
||
| }, | ||
| "설정" : { | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,287 @@ | ||
| // | ||
| // UIKitTextEditor.swift | ||
| // DevLog | ||
| // | ||
| // Created by opfic on 3/18/26. | ||
| // | ||
|
|
||
| import SwiftUI | ||
| import UIKit | ||
|
|
||
| struct UIKitTextEditor: View { | ||
| @Binding var text: String | ||
| @Environment(\.uiKitTextEditorFocusBinding) private var focusBinding | ||
| @State private var minHeight = TextEditorMetrics.font.lineHeight | ||
| private let placeholder: String | ||
|
|
||
| init( | ||
| text: Binding<String>, | ||
| placeholder: String = "" | ||
| ) { | ||
| self._text = text | ||
| self.placeholder = placeholder | ||
| } | ||
|
|
||
| var body: some View { | ||
| UIKitTextEditorRepresentable( | ||
| text: $text, | ||
| minHeight: $minHeight, | ||
| focusBinding: focusBinding, | ||
| placeholder: placeholder | ||
| ) | ||
| .frame(maxWidth: .infinity, minHeight: minHeight) | ||
| } | ||
|
|
||
| // 각 메서드 내에 있는 `.focused()`의 정체 | ||
| // 해당 .focused()는 SwiftUI의 모디파이어 | ||
| // 이 뷰를 SwiftUI 포커스 시스템에 실제 포커스 타겟으로 등록해주는 역할을 함 | ||
|
|
||
| func focused(_ condition: FocusState<Bool>.Binding) -> some View { | ||
| modifier(TextEditorFocusModifier( | ||
| focusBinding: Binding(condition) | ||
| )) | ||
| .focused(condition) | ||
| } | ||
|
|
||
| func focused<Value>( | ||
| _ binding: FocusState<Value>.Binding, | ||
| equals value: Value | ||
| ) -> some View where Value: Hashable & ExpressibleByNilLiteral { | ||
| modifier(TextEditorFocusModifier( | ||
| focusBinding: Binding( | ||
| binding, | ||
| equals: value | ||
| ) | ||
| )) | ||
| .focused(binding, equals: value) | ||
| } | ||
| } | ||
|
|
||
| private enum TextEditorMetrics { | ||
| static let font = UIFont.preferredFont(forTextStyle: .body) | ||
| } | ||
|
|
||
| private struct TextEditorFocusModifier: ViewModifier { | ||
| let focusBinding: Binding<Bool> | ||
|
|
||
| func body(content: Content) -> some View { | ||
| content | ||
| .environment(\.uiKitTextEditorFocusBinding, focusBinding) | ||
| } | ||
| } | ||
|
|
||
| private struct TextEditorFocusBindingKey: EnvironmentKey { | ||
| static let defaultValue: Binding<Bool>? = nil | ||
| } | ||
|
|
||
| private extension EnvironmentValues { | ||
| var uiKitTextEditorFocusBinding: Binding<Bool>? { | ||
| get { self[TextEditorFocusBindingKey.self] } | ||
| set { self[TextEditorFocusBindingKey.self] = newValue } | ||
| } | ||
| } | ||
|
|
||
| private struct UIKitTextEditorRepresentable: UIViewRepresentable { | ||
| @Binding var text: String | ||
| @Binding var minHeight: CGFloat | ||
| private let focusBinding: Binding<Bool>? | ||
| private let placeholder: String | ||
|
|
||
| init( | ||
| text: Binding<String>, | ||
| minHeight: Binding<CGFloat>, | ||
| focusBinding: Binding<Bool>?, | ||
| placeholder: String | ||
| ) { | ||
| self._text = text | ||
| self.focusBinding = focusBinding | ||
| self._minHeight = minHeight | ||
| self.placeholder = placeholder | ||
| } | ||
|
|
||
| func makeCoordinator() -> Coordinator { | ||
| Coordinator(self) | ||
| } | ||
|
|
||
| func makeUIView(context: Context) -> UITextView { | ||
| let textView = UITextView() | ||
| textView.delegate = context.coordinator | ||
| textView.font = TextEditorMetrics.font | ||
| textView.backgroundColor = .clear | ||
| textView.textColor = .label | ||
| textView.tintColor = .tintColor | ||
| textView.textContainer.lineFragmentPadding = 0 | ||
| textView.textContainer.widthTracksTextView = true | ||
| textView.textContainer.lineBreakMode = .byWordWrapping | ||
| textView.textContainerInset = .zero | ||
| textView.isScrollEnabled = false | ||
| textView.autocorrectionType = .no | ||
| textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) | ||
| textView.setContentHuggingPriority(.defaultLow, for: .horizontal) | ||
| context.coordinator.applyPlaceholderIfNeeded(to: textView) | ||
| return textView | ||
| } | ||
|
|
||
| func updateUIView(_ uiView: UITextView, context: Context) { | ||
| context.coordinator.parent = self | ||
|
|
||
| if !context.coordinator.isShowingPlaceholder(in: uiView) && uiView.text != text { | ||
| uiView.text = text | ||
| } | ||
|
|
||
| context.coordinator.applyPlaceholderIfNeeded(to: uiView) | ||
|
|
||
| DispatchQueue.main.async { | ||
| if let focusBinding { | ||
| if focusBinding.wrappedValue { | ||
| if !uiView.isFirstResponder { | ||
| context.coordinator.preserveAncestorScrollOffset(for: uiView) | ||
| uiView.becomeFirstResponder() | ||
| } | ||
| } else if uiView.isFirstResponder { | ||
| uiView.resignFirstResponder() | ||
| } | ||
| } | ||
| context.coordinator.updateHeight(for: uiView) | ||
| } | ||
| } | ||
|
|
||
| final class Coordinator: NSObject, UITextViewDelegate { | ||
| var parent: UIKitTextEditorRepresentable | ||
| private weak var ancestorScrollView: UIScrollView? | ||
| private var preservedContentOffset: CGPoint? | ||
|
|
||
| init(_ parent: UIKitTextEditorRepresentable) { | ||
| self.parent = parent | ||
| } | ||
|
|
||
| func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { | ||
| preserveAncestorScrollOffset(for: textView) | ||
| return true | ||
| } | ||
|
|
||
| func textViewDidBeginEditing(_ textView: UITextView) { | ||
| if isShowingPlaceholder(in: textView) { | ||
| textView.text = nil | ||
| textView.textColor = .label | ||
| } | ||
|
|
||
| if let focusBinding = parent.focusBinding, !focusBinding.wrappedValue { | ||
| focusBinding.wrappedValue = true | ||
| } | ||
|
|
||
| restoreAncestorScrollOffsetIfNeeded() | ||
|
|
||
| DispatchQueue.main.async { [weak self] in | ||
| self?.restoreAncestorScrollOffsetIfNeeded() | ||
| self?.updateHeight(for: textView) | ||
| } | ||
|
|
||
| DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in | ||
| self?.restoreAncestorScrollOffsetIfNeeded() | ||
| self?.preservedContentOffset = nil | ||
| } | ||
| } | ||
|
|
||
| func textViewDidChange(_ textView: UITextView) { | ||
| parent.text = textView.text | ||
| updateHeight(for: textView) | ||
| } | ||
|
|
||
| func textViewDidEndEditing(_ textView: UITextView) { | ||
| if let focusBinding = parent.focusBinding, focusBinding.wrappedValue { | ||
| focusBinding.wrappedValue = false | ||
| } | ||
|
|
||
| applyPlaceholderIfNeeded(to: textView) | ||
| } | ||
|
|
||
| func applyPlaceholderIfNeeded(to textView: UITextView) { | ||
| if parent.text.isEmpty && !textView.isFirstResponder { | ||
| textView.text = parent.placeholder | ||
| textView.textColor = .placeholderText | ||
| } else if isShowingPlaceholder(in: textView) { | ||
| textView.text = parent.text | ||
| textView.textColor = .label | ||
| } | ||
| } | ||
|
|
||
| func isShowingPlaceholder(in textView: UITextView) -> Bool { | ||
| textView.textColor == .placeholderText | ||
| } | ||
|
|
||
| func preserveAncestorScrollOffset(for textView: UITextView) { | ||
| ancestorScrollView = textView.enclosingScrollView | ||
| preservedContentOffset = ancestorScrollView?.contentOffset | ||
| } | ||
|
|
||
| func restoreAncestorScrollOffsetIfNeeded() { | ||
| guard let ancestorScrollView, let preservedContentOffset else { return } | ||
|
|
||
| if ancestorScrollView.contentOffset != preservedContentOffset { | ||
| ancestorScrollView.setContentOffset(preservedContentOffset, animated: false) | ||
| } | ||
| } | ||
|
|
||
| func updateHeight(for textView: UITextView) { | ||
| textView.layoutIfNeeded() | ||
|
|
||
| let width = textView.bounds.width | ||
| guard 0 < width else { return } | ||
|
|
||
| let nextHeight = ceil(textView.sizeThatFits( | ||
| CGSize(width: width, height: .greatestFiniteMagnitude) | ||
| ).height) | ||
| let resolvedHeight = max(nextHeight, TextEditorMetrics.font.lineHeight) | ||
|
|
||
| if parent.minHeight != resolvedHeight { | ||
| DispatchQueue.main.async { | ||
| self.parent.minHeight = resolvedHeight | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private extension Binding where Value == Bool { | ||
| init(_ binding: FocusState<Bool>.Binding) { | ||
| self.init( | ||
| get: { binding.wrappedValue }, | ||
| set: { binding.wrappedValue = $0 } | ||
| ) | ||
| } | ||
|
|
||
| init<FocusedValue>( | ||
| _ binding: FocusState<FocusedValue>.Binding, | ||
| equals value: FocusedValue | ||
| ) where FocusedValue: Hashable & ExpressibleByNilLiteral { | ||
| self.init( | ||
| get: { | ||
| binding.wrappedValue == value | ||
| }, | ||
| set: { isFocused in | ||
| if isFocused { | ||
| binding.wrappedValue = value | ||
| } else if binding.wrappedValue == value { | ||
| binding.wrappedValue = nil | ||
| } | ||
| } | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| private extension UIView { | ||
| var enclosingScrollView: UIScrollView? { | ||
| var currentSuperview = superview | ||
|
|
||
| while let view = currentSuperview { | ||
| if let scrollView = view as? UIScrollView { | ||
| return scrollView | ||
| } | ||
|
|
||
| currentSuperview = view.superview | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -95,8 +95,7 @@ struct TodoEditorView: View { | |||||
| } | ||||||
| Divider() | ||||||
| Button(action: { | ||||||
| viewModel.send(.setTabViewTag(.preview)) | ||||||
| field = nil | ||||||
| transitionToPreview() | ||||||
| }) { | ||||||
| Text("미리보기") | ||||||
| .frame(maxWidth: .infinity) | ||||||
|
|
@@ -115,16 +114,13 @@ struct TodoEditorView: View { | |||||
| if viewModel.state.tabViewTag == .editor { | ||||||
| VStack(alignment: .leading, spacing: 8) { | ||||||
| markdownHint | ||||||
| TextField( | ||||||
| "", | ||||||
| UIKitTextEditor( | ||||||
| text: Binding( | ||||||
| get: { viewModel.state.content }, | ||||||
| set: { viewModel.send(.setContent($0)) } | ||||||
| ), | ||||||
| prompt: Text("설명(선택)").foregroundColor(Color.secondary), | ||||||
| axis: .vertical | ||||||
| placeholder: "설명(선택)" | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| ) | ||||||
| .font(.callout) | ||||||
| .focused($field, equals: .content) | ||||||
| } | ||||||
| } else { | ||||||
|
|
@@ -164,6 +160,14 @@ struct TodoEditorView: View { | |||||
| dismiss() | ||||||
| } | ||||||
|
|
||||||
| private func transitionToPreview() { | ||||||
| field = nil | ||||||
|
|
||||||
| DispatchQueue.main.async { | ||||||
| viewModel.send(.setTabViewTag(.preview)) | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| private enum Field: Hashable { | ||||||
| case title, content | ||||||
| } | ||||||
|
|
||||||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
DispatchQueue.main.asyncAfter를 사용하여 0.1초의 고정된 지연 시간을 주는 것은 불안정할 수 있습니다. 디바이스의 성능이나 시스템 상태에 따라 이 시간이 충분하지 않아 버그가 발생할 수 있습니다.더 안정적인 방법으로
UIResponder.keyboardWillShowNotification또는UIResponder.keyboardDidShowNotification과 같은 키보드 노티피케이션을 구독하여 키보드 애니메이션과 동기화하거나,UIScrollView의contentOffset을 KVO로 관찰하여 변경에 대응하는 것을 고려해 보시는 것이 좋겠습니다.