Created
October 30, 2021 10:00
-
-
Save diamantidis/365be7bbd66919e0b6f21986ec68b864 to your computer and use it in GitHub Desktop.
PickerTextField for medium post
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
import SwiftUI | |
class PickerTextField: UITextField { | |
// MARK: - Public properties | |
var data: [String] | |
@Binding var selectionIndex: Int? | |
// MARK: - Initializers | |
init(data: [String], selectionIndex: Binding<Int?>) { | |
self.data = data | |
self._selectionIndex = selectionIndex | |
super.init(frame: .zero) | |
self.inputView = pickerView | |
self.inputAccessoryView = toolbar | |
self.tintColor = .clear | |
guard let selectionIndex = selectionIndex.wrappedValue else { | |
return | |
} | |
self.pickerView.selectRow(selectionIndex, inComponent: 0, animated: true) | |
} | |
@available(*, unavailable) | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
// MARK: - Private properties | |
private lazy var pickerView: UIPickerView = { | |
let pickerView = UIPickerView() | |
pickerView.delegate = self | |
pickerView.dataSource = self | |
return pickerView | |
}() | |
private lazy var toolbar: UIToolbar = { | |
let toolbar = UIToolbar() | |
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) | |
let doneButton = UIBarButtonItem( | |
title: "Done", | |
style: .done, | |
target: self, | |
action: #selector(donePressed) | |
) | |
toolbar.setItems([flexibleSpace, doneButton], animated: false) | |
toolbar.sizeToFit() | |
return toolbar | |
}() | |
// MARK: - Private methods | |
@objc | |
private func donePressed() { | |
self.selectionIndex = self.pickerView.selectedRow(inComponent: 0) | |
self.endEditing(true) | |
} | |
} | |
// MARK: - UIPickerViewDataSource & UIPickerViewDelegate extension | |
extension PickerTextField: UIPickerViewDataSource, UIPickerViewDelegate { | |
func numberOfComponents(in pickerView: UIPickerView) -> Int { | |
return 1 | |
} | |
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { | |
return self.data.count | |
} | |
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { | |
return self.data[row] | |
} | |
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { | |
self.selectionIndex = row | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment