Я хотел бы создать uiviewrepresentable , удерживающее uitextfield с использованием uidatepicker в качестве inputview
, в то время как код ниже работает нормально, тогда дата DatePicker непосредственно используется в код/код/код. Добавить дополнительные элементы управления).
Ни добавление ограничения размера в дату -пикер или ContainErview и не используя ContainErview с внутренним размером, изменил результат.struct DatePickerTextField: UIViewRepresentable {
private let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
return dateFormatter
}()
public var placeholder: String
@Binding public var date: Date?
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
let datePicker = UIDatePicker()
let container = DatePickerContainer()
datePicker.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(datePicker)
NSLayoutConstraint.activate([
datePicker.leadingAnchor.constraint(equalTo: container.leadingAnchor),
datePicker.trailingAnchor.constraint(equalTo: container.trailingAnchor),
datePicker.topAnchor.constraint(equalTo: container.topAnchor),
datePicker.bottomAnchor.constraint(equalTo: container.bottomAnchor),
//datePicker.heightAnchor.constraint(equalToConstant: 300)
])
datePicker.datePickerMode = .date
datePicker.preferredDatePickerStyle = .inline
//textField.inputView = datePicker // correct height
textField.inputView = container
// Accessory View
let toolbar = UIToolbar()
toolbar.sizeToFit()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done",
style: .plain,
target: context.coordinator,
action: #selector(context.coordinator.doneButtonAction))
toolbar.setItems([flexibleSpace, doneButton], animated: true)
textField.inputAccessoryView = toolbar
context.coordinator.dateChanged = {
self.date = datePicker.date
}
context.coordinator.doneButtonTapped = {
if self.date == nil {
self.date = datePicker.date
}
textField.resignFirstResponder()
}
return textField
}
class DatePickerContainer: UIView {
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: 300)
}
}
func updateUIView(_ uiView: UITextField, context: Context) {
if let selectedDate = self.date {
uiView.text = self.dateFormatter.string(from: selectedDate)
}
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator {
public var dateChanged: (() -> Void)?
public var doneButtonTapped: (() -> Void)?
@objc func dateValueChanged() {
self.dateChanged?()
}
@objc func doneButtonAction() {
self.doneButtonTapped?()
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... resentable