-
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 all 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,332 @@ | ||
| // | ||
| // 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.startTrackingOffset(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 scrollView: UIScrollView? | ||
| private var offsetObservation: NSKeyValueObservation? | ||
| private var trackedOffset: CGPoint? | ||
| private var isRestoringOffset = false | ||
|
|
||
| init(_ parent: UIKitTextEditorRepresentable) { | ||
| self.parent = parent | ||
| } | ||
|
|
||
| func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { | ||
| startTrackingOffset(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 | ||
| } | ||
|
|
||
| restoreOffsetIfNeeded() | ||
|
|
||
| DispatchQueue.main.async { [weak self] in | ||
| self?.restoreOffsetIfNeeded() | ||
| self?.updateHeight(for: textView) | ||
| } | ||
| } | ||
|
|
||
| func textViewDidChange(_ textView: UITextView) { | ||
| stopTrackingOffset() | ||
| parent.text = textView.text | ||
| updateHeight(for: textView) | ||
| } | ||
|
|
||
| func textViewDidEndEditing(_ textView: UITextView) { | ||
| if let focusBinding = parent.focusBinding, focusBinding.wrappedValue { | ||
| focusBinding.wrappedValue = false | ||
| } | ||
|
|
||
| stopTrackingOffset() | ||
| 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 startTrackingOffset(for textView: UITextView) { | ||
| stopObservingOffset() | ||
| scrollView = textView.enclosingScrollView | ||
| trackedOffset = scrollView?.contentOffset | ||
| observeOffsetIfNeeded() | ||
| } | ||
|
|
||
| func restoreOffsetIfNeeded() { | ||
| guard let scrollView, let trackedOffset else { return } | ||
|
|
||
| if scrollView.contentOffset != trackedOffset { | ||
| isRestoringOffset = true | ||
| scrollView.setContentOffset(trackedOffset, animated: false) | ||
| isRestoringOffset = false | ||
| } | ||
| } | ||
|
|
||
| func observeOffsetIfNeeded() { | ||
| guard let scrollView else { return } | ||
|
|
||
| offsetObservation = scrollView.observe( | ||
| \.contentOffset, | ||
| options: [.new] | ||
| ) { [weak self] scrollView, _ in | ||
| self?.handleOffsetChange(in: scrollView) | ||
| } | ||
| } | ||
|
|
||
| func handleOffsetChange(in scrollView: UIScrollView) { | ||
| guard let trackedOffset else { | ||
| stopObservingOffset() | ||
| return | ||
| } | ||
|
|
||
| if scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating { | ||
| stopTrackingOffset() | ||
| return | ||
| } | ||
|
|
||
| if isRestoringOffset { | ||
| return | ||
| } | ||
|
|
||
| if scrollView.contentOffset != trackedOffset { | ||
| restoreOffsetIfNeeded() | ||
| } | ||
| } | ||
|
|
||
| func stopObservingOffset() { | ||
| offsetObservation?.invalidate() | ||
| offsetObservation = nil | ||
| } | ||
|
|
||
| func stopTrackingOffset() { | ||
| stopObservingOffset() | ||
| scrollView = nil | ||
| trackedOffset = nil | ||
| } | ||
|
|
||
| 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
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.
placeholder에 문자열을 직접 하드코딩하면 국제화가 지원되지 않는 문제가 있습니다. 기존TextField의prompt에서는Text뷰를 통해 자동적으로 지역화가 이루어졌습니다.Localizable.xcstrings파일에"설명(선택)"키를 다시 추가하고, 이 곳에서는String(localized: "설명(선택)")또는NSLocalizedString를 사용하여 지역화된 문자열을 사용하도록 수정하는 것이 좋겠습니다.