To show a list instead of the keyboard, set the text field's inputView to a view that contains a UITableView. A UIInputView with the .keyboard style matches the keyboard's background. Keep the selected row in your data and set the checkmark in cellForRowAt every time. If you set it on the cell object when a row is tapped, as the 2018 code did, the checkmark jumps to other rows when cells are reused. Close the list with resignFirstResponder() on the text field.
SWIFT TIPS · UIKIT · UITEXTFIELD
First posted on May 8, 2018 for Swift 4, as "Custom KeyBoard Use UITableView Swift 4 Xcode 9". Rewritten on November 18, 2026. The table tests were run on a Mac as a Mac Catalyst program, which runs UIKit on macOS (not an iPhone or the simulator), with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. The code was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 and iOS 26.2 as deployment targets, but not run on a device.
In 2018 I wanted a text field that opens a list of choices from the API instead of the keyboard. The post loaded a custom view from a XIB file, put a table view in it, and assigned it to the text field's inputView inside a button action. Tapping a row put a checkmark on that cell, and a button sent the choice back through a delegate.
Replacing the keyboard with your own view is still exactly what inputView is for. Apple's documentation describes it as the view that replaces the system keyboard for text fields and text views. Two parts of the 2018 code are worth changing: where the checkmark lives and how the list closes.
The checkmark that moves
The 2018 table set cell.accessoryType = .checkmark in didSelectRowAt, and cellForRowAt only set the text. I built that table with 40 rows, tapped the first row, scrolled down and back up, and listed the visible rows that had a checkmark. I did the same with the new code:
2018 code (checkmark set on the cell):
after tapping Item 1, rows with a checkmark: ["Item 1"]
scrolled to Item 11-16: checkmarks on []
scrolled to Item 21-26: checkmarks on ["Item 26"]
scrolled to Item 31-36: checkmarks on []
scrolled to Item 1-6: checkmarks on ["Item 6"]
New code (checkmark from the data):
after tapping Item 1, rows with a checkmark: ["Item 1"]
scrolled to Item 11-16: checkmarks on []
scrolled to Item 21-26: checkmarks on []
scrolled to Item 31-36: checkmarks on []
scrolled to Item 1-6: checkmarks on ["Item 1"]
A table view only creates enough cells to fill the screen and reuses them as you scroll. The cell that showed "Item 1" was reused for "Item 26", still carrying its checkmark. Back at the top, "Item 1" had lost its checkmark and "Item 6" had one. Apple's documentation for prepareForReuse() says the table's cellForRowAt should always reset all content when a cell is reused, and the checkmark is content.
A list that replaces the keyboard
import UIKit
struct Choice: Hashable, Sendable {
let id: String
let name: String
}
/// A list that appears in place of the keyboard. Tapping a row picks it; Done closes the list.
final class ChoiceKeyboardView: UIInputView, UITableViewDataSource, UITableViewDelegate {
var choices: [Choice] = [] { didSet { tableView.reloadData() } }
private(set) var selected: Choice?
var onPick: ((Choice) -> Void)?
var onDone: (() -> Void)?
private let tableView = UITableView(frame: .zero, style: .plain)
private let doneButton = UIButton(type: .system)
init(height: CGFloat = 260) {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: height), inputViewStyle: .keyboard)
autoresizingMask = .flexibleWidth // the system sets the width; the height stays ours
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "choice")
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = .clear
doneButton.setTitle("Done", for: .normal)
doneButton.titleLabel?.font = .preferredFont(forTextStyle: .headline)
doneButton.addAction(UIAction { [weak self] _ in self?.onDone?() }, for: .touchUpInside)
let stack = UIStackView(arrangedSubviews: [doneButton, tableView])
stack.axis = .vertical
stack.alignment = .fill
stack.translatesAutoresizingMaskIntoConstraints = false
addSubview(stack)
NSLayoutConstraint.activate([
stack.leadingAnchor.constraint(equalTo: leadingAnchor),
stack.trailingAnchor.constraint(equalTo: trailingAnchor),
stack.topAnchor.constraint(equalTo: topAnchor),
stack.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor),
doneButton.heightAnchor.constraint(equalToConstant: 44),
])
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
choices.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "choice", for: indexPath)
let choice = choices[indexPath.row]
var content = cell.defaultContentConfiguration()
content.text = choice.name
cell.contentConfiguration = content
// Set the checkmark from the data every time. A reused cell must not keep an old one.
cell.accessoryType = choice == selected ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let previous = selected.flatMap { choices.firstIndex(of: $0) }.map { IndexPath(row: $0, section: 0) }
selected = choices[indexPath.row]
tableView.reloadRows(at: [previous, indexPath].compactMap { $0 }, with: .none)
onPick?(choices[indexPath.row])
}
}
final class CarBrandViewController: UIViewController {
private let brandField = UITextField()
private let keyboard = ChoiceKeyboardView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
brandField.placeholder = "Car brand"
brandField.borderStyle = .roundedRect
brandField.tintColor = .clear // no blinking cursor in a field you can't type in
brandField.inputView = keyboard
keyboard.choices = ["Daihatsu", "Honda", "Mitsubishi", "Suzuki", "Toyota"]
.map { Choice(id: $0.lowercased(), name: $0) }
keyboard.onPick = { [weak self] choice in self?.brandField.text = choice.name }
keyboard.onDone = { [weak self] in self?.brandField.resignFirstResponder() }
brandField.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(brandField)
NSLayoutConstraint.activate([
brandField.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
brandField.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
brandField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
])
}
}
I also ran ChoiceKeyboardView on its own in the Catalyst program, at 320 points wide, and sent two row taps through its delegate methods:
height 260.0 pt, rows visible: 5
tap Honda: field "Honda", checkmarks ["Honda"]
tap Toyota: field "Toyota", checkmarks ["Toyota"]
How it works
- The input view is set once.
brandField.inputView = keyboardruns inviewDidLoad. When the field becomes first responder, the system shows the list in place of the keyboard, and when it resigns, the list goes away. The 2018 code set it in a button action. Apple's documentation describes the input view as what the field shows when it becomes first responder, andreloadInputViews()as the way to refresh it while the field is already first responder, so a change made mid-edit needs that call. - The height is yours, the width is the system's. The view is created 260 points high.
autoresizingMask = .flexibleWidthlets the system stretch it to the screen width. - The selection lives in the data.
selectedholds the chosenChoice.cellForRowAtsets the checkmark from it every time, and a tap reloads only the old and the new row. - Closures instead of a delegate protocol.
onPickandonDonedo the job of the 2018KeyboardLDelegatewith less code. If you prefer a delegate, declare it asprotocol ChoiceKeyboardDelegate: AnyObject: the 2018 form,: class, now gives the warning shown below. - Closing the list. Done calls
resignFirstResponder()on the text field. The 2018 button calledremoveFromSuperview()on the keyboard view itself, which takes the view out without telling the text field it stopped editing. - No cursor.
tintColor = .clearhides the blinking cursor, since the field can only be filled from the list.
Things the 2018 code needed that the new code doesn't
- A XIB and an outlet. The view loaded
keyView.xiband a cell fromApiTableViewCell.xib. The new view builds its two subviews in code and uses the system cell withdefaultContentConfiguration(). - Setup in both initializers. The 2018 view connected the table's delegate and data source only in
init(frame:), so loading it from a storyboard throughinit?(coder:)would have left the table empty. - A hidden separator trick.
separatorInsetwas set to the screen width, which pushes the separator lines off screen. If you don't want them,tableView.separatorStyle = .nonesays so directly.
The Swift compiler also flags the old protocol declaration:
o014_proto.swift:1:29: warning: using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead [#deprecation]
A quick check for your project
- Search for
accessoryType = .checkmarkinsidedidSelectRowAt. IfcellForRowAtdoesn't set the accessory type for every row, scroll a long list and watch the checkmarks. - Search for
inputView =inside button actions or text field callbacks. If the field may already be editing, callreloadInputViews()right after. - Search for
: class {in protocol declarations and change it to: AnyObject.
What the 2018 version said
The original had a KeyBoardViewController with two text fields and a keyviewF view class with a PickerDataSource1 model of id and name. Its delegate method inserted the fixed text "hi D" into the second field rather than the chosen name. The post linked to a source download on Zippyshare, a file host that has since shut down, so I removed the link.
Keep reading on JR Devhub
Comments