我有以下功能,可添加下一个和上一个按钮,这些按钮将在文本字段之间切换,以提供更好的用户体验。但是,我无法通过警报控制器内的文本字段实现此功能。有解决方案还是我必须考虑我的应用程序的另一种设计?
extension UIViewController {
func addInputAccessoryForTextFields(textFields: [UITextField], dismissable: Bool = true, previousNextable: Bool = false) {
for (index, textField) in textFields.enumerated() {
let toolbar: UIToolbar = UIToolbar()
toolbar.sizeToFit()
var items = [UIBarButtonItem]()
if previousNextable {
let previousButton = UIBarButtonItem(image: UIImage(named: "previous"), style: .plain, target: nil, action: nil)
previousButton.width = 30
if textField == textFields.first {
previousButton.isEnabled = false
} else {
previousButton.target = textFields[index - 1]
previousButton.action = #selector(UITextField.becomeFirstResponder)
}
let nextButton = UIBarButtonItem(image: UIImage(named: "next"), style: .plain, target: nil, action: nil)
nextButton.width = 30
if textField == textFields.last {
nextButton.isEnabled = false
} else {
nextButton.target = textFields[index + 1]
nextButton.action = #selector(UITextField.becomeFirstResponder)
}
items.append(contentsOf: [previousButton, nextButton])
}
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: view, action: #selector(UIView.endEditing))
items.append(contentsOf: [spacer, doneButton])
toolbar.setItems(items, animated: false)
textField.inputAccessoryView = toolbar
}
}
}
这是我的警报控制器,我在其中声明警报并添加警告:
alertDisplay.addTextField { (textField) in
textField.placeholder = "Enter Team 1 Score"
textField.keyboardType = UIKeyboardType.decimalPad
}
alertDisplay.addTextField { (textField) in
textField.placeholder = "Enter Team 2 Score"
textField.keyboardType = UIKeyboardType.decimalPad
}
要调用该函数,我必须在数组中添加我想要的文本字段(这将允许下一个和上一个字段通过文本字段)。在viewDidLoad()方法中调用此函数。
所以问题是如何让警报中的两个文本字段为键盘设置这个自定义工具栏?