60 lines
1.8 KiB
Swift
60 lines
1.8 KiB
Swift
//
|
|
// TextField.swift
|
|
// Malinka
|
|
//
|
|
// Created by NUT.Tech on 08.02.2023.
|
|
// Copyright © 2023 NUT.Tech. All rights reserved.
|
|
//
|
|
|
|
import SwiftUI
|
|
import Combine
|
|
|
|
/// Struct can be replaced to SwiftUI's native TextField after iOS 15.0.
|
|
/// It was created for access to firstResponder logic which has no analogue
|
|
/// until iOS 15.0 with @FocusState wrapper type and isFocused property of TextField.
|
|
|
|
public struct TextField: UIViewRepresentable {
|
|
|
|
@ObservedObject
|
|
public var viewModel: TextFieldViewModel
|
|
public let font: UIFont
|
|
public let textColor: UIColor
|
|
|
|
// MARK: - Init
|
|
|
|
public init(viewModel: TextFieldViewModel, font: UIFont, textColor: UIColor) {
|
|
self.viewModel = viewModel
|
|
self.font = font
|
|
self.textColor = textColor
|
|
}
|
|
|
|
// MARK: - UIViewRepresentable
|
|
|
|
public func makeCoordinator() -> UITextFieldDelegate {
|
|
TextFieldCoordinator(viewModel: self.viewModel)
|
|
}
|
|
|
|
public func makeUIView(context: Context) -> UITextField {
|
|
let view = UITextField()
|
|
view.autocapitalizationType = .none
|
|
view.autocorrectionType = .no
|
|
view.clearButtonMode = .never
|
|
view.font = font
|
|
view.textColor = self.textColor
|
|
view.keyboardType = self.viewModel.keyboardType
|
|
view.placeholder = self.viewModel.placeholder
|
|
view.addTarget(context.coordinator,
|
|
action: #selector(TextFieldCoordinator.textViewDidChange),
|
|
for: .editingChanged)
|
|
view.delegate = context.coordinator
|
|
return view
|
|
}
|
|
|
|
public func updateUIView(_ uiView: UITextField, context: Context) {
|
|
uiView.text = self.viewModel.text
|
|
self.viewModel.isFirstResponder
|
|
? uiView.becomeFirstResponder()
|
|
: uiView.resignFirstResponder()
|
|
}
|
|
}
|