以下のコードをカスタムクラスに書いて、InterFaceBuilderでtextFieldのCustom Classにそのクラス名(PickerText)を指定してシュミレータを起動しました。決定ボタン(UIBarButtonItem)を押したところ、unrecognized selector sent to instance 0x7fe24e407e10というエラーが出ました。Custom Class名や#selecterを確認しましたが合っている様です。この解決方法をご教授ください。
Swift
1import Foundation 2import UIKit 3 4class PickerText: UITextField { 5 6 var datePicker: UIDatePicker! 7 8 required init?(coder: NSCoder) { 9 super.init(coder: coder) 10 commoninit() 11 } 12 override init(frame: CGRect) { 13 super.init(frame: frame) 14 commoninit() 15 } 16 17 func commoninit(){ 18 19 datePicker = UIDatePicker() 20 datePicker.date = Date() 21 datePicker.datePickerMode = .date 22 datePicker.locale = Locale(identifier: "ja") 23 datePicker.addTarget(self, action: #selector(setText), for: .valueChanged) 24 setText() 25 26 inputView = datePicker 27 inputAccessoryView = createToolbar() 28 29 } 30 31 32 func createToolbar() -> UIToolbar { 33 let toolbar = UIToolbar() 34 toolbar.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 44) 35 36 let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: self, action: nil) 37 space.width = 12 38 let flexSpaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) 39 let todayButtonItem = UIBarButtonItem(title: "今日", style: .done, target: self, action: #selector(todayPicker)) 40 let doneButtonItem = UIBarButtonItem(title: "決定", style: .done, target: self, action: #selector(donePicker)) 41 42 let toolbarItems = [space, flexSpaceItem, todayButtonItem, doneButtonItem] 43 toolbar.setItems(toolbarItems, animated: true) 44 45 return toolbar 46 } 47 48 @objc func todayPicker() { 49 datePicker.date = Date() 50 setText() 51 } 52 53 @objc private func donePicker() { 54 setText() 55 self.endEditing(true) 56 } 57 58 @objc func setText(){ 59 let f = DateFormatter() 60 f.calendar = Calendar(identifier: .japanese) 61 f.dateStyle = .long 62 f.locale = Locale(identifier: "ja") 63 text = f.string(from: datePicker.date) 64 65 } 66 67 68 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { 69 return false 70 } 71 72 override func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { 73 return [] 74 } 75 76 override func caretRect(for position: UITextPosition) -> CGRect { 77 return CGRect(x: 0, y: 0, width: 0, height:0) 78 } 79 80}
回答1件
あなたの回答
tips
プレビュー