我有一个自定义的选择器视图,并连接两个文本字段。
但我对我的挑选者提出了一些疑问。
pickerview有一个工具栏和两个barbuttonitems(完成并取消)。
当我点击textfield1时。完成和完成取消没有采取行动
然后我点击textfield2。完成和完成取消也不要采取行动。
最后我回来点击textfield1。按钮叫我取消&功能成功。
我想问一下如何让我的按钮在第一次点击时间工作。
这是自定义pickerview中的代码:
import UIKit
import SnapKit
class PickerView: UIView {
var toolbar:UIToolbar = UIToolbar()
var picker :UIPickerView = UIPickerView()
var done :UIBarButtonItem = UIBarButtonItem()
var cancel :UIBarButtonItem = UIBarButtonItem()
override init(frame: CGRect) {
super.init(frame:frame)
translatesAutoresizingMaskIntoConstraints = false
loadContent()
}
func loadContent() {
toolbar.sizeToFit()
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolbar.items = [cancel,flexSpace,done]
addSubview(toolbar)
addSubview(picker)
}
}
的ViewController
import UIKit
class ViewController: UIViewController , UIPickerViewDelegate , UIPickerViewDataSource {
var textField1:UITextField = UITextField()
var textField2:UITextField = UITextField()
var pick1:PickerView = PickerView()
var pick2:PickerView = PickerView()
override func loadView() {
super.loadView()
loadElement()
}
func loadElement() {
view.addSubview(textField1)
view.addSubview(textField2)
}
override func viewDidLoad() {
super.viewDidLoad()
pick1.picker.delegate = self
pick1.picker.dataSource = self
pick2.picker.delegate = self
pick2.picker.dataSource = self
textField1.inputView = pick1.picker
textField1.inputAccessoryView = pick1.toolbar
textField2.inputView = pick2.picker
textField2.inputAccessoryView = pick2.toolbar
//pickerview setting
pick1.picker.showsSelectionIndicator = true
pick1.picker.tag = 0
pick1.done.action = #selector(done1Clicked)
pick1.cancel.action = #selector(cancel1Clicked)
pick2.picker.showsSelectionIndicator = true
pick2.picker.tag = 1
pick2.done.action = #selector(done2Clicked)
pick2.cancel.action = #selector(cancel2Clicked)
}
//don't call these functions !!!!!!
func cancel1Clicked(sender:UIBarButtonItem) {
textField1.resignFirstResponder()
}
func done1Clicked(sender:UIBarButtonItem) {
textField1.resignFirstResponder()
}
func cancel2Clicked(sender:UIBarButtonItem) {
textField2.resignFirstResponder()
}
func done2Clicked(sender:UIBarButtonItem) {
textField2.resignFirstResponder()
}
}