我无法使用回调作为完成处理程序在类之间传递数据

我想将自定义类中的textField文本传递给ViewController并在点击DatePicker的BarButtonItem时将其填充到数组中。我使用回调作为完成处理程序,但它捕获了EXC-BAD-ACCESS。是什么导致此错误,以及如何将文本传递给ViewController?

  • 自定义的textField类
class HourDatePicker: UITextField {

    var datePicker =  UIDatePicker()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commominit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commominit()
    }

    func commominit(){
        text = ""
        datePicker.datePickerMode = .dateAndTime
        datePicker.minuteInterval = 30
        datePicker.locale = Locale(identifier: "ja")
        datePicker.addTarget(self, action: #selector(setText), for: .valueChanged)
        setText()
        inputView = datePicker
        inputAccessoryView = customPicker()
     }

    @objc func setText(){
        let f = DateFormatter()
        f.dateStyle = .full
        f.timeStyle = .short
        f.locale = Locale(identifier: "ja")
        textColor = .black
        text = "\(f.string(from: datePicker.date))"

    }
    private func customPicker() -> UIToolbar {
        let toolbar = UIToolbar()
        toolbar.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: 40)
        let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: self, action: nil)
        space.width = 100
        let flexSpaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let todayButtonItem = UIBarButtonItem(title: "today", style: .done, target: self, action: #selector(setToday))
        let selectButtonItem = UIBarButtonItem(title: "select", style: .done, target: self, action: #selector(tellCalenderText))

        let toolbarItem = [space, flexSpaceItem, todayButtonItem, selectButtonItem]
         toolbar.setItems(toolbarItem, animated: true)
        }
        return toolbar
    }

    @objc func tellCalenderText(completion: ((_ titleText: String) -> Void)){
        //I want to pass text here.
        if text != "" {
        guard let titleText = text else {return}
        completion(titleText)
        } else {
            return
        }

    }
  • ViewController
class Calender1ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    private let selectDate = HourDatePicker()
    private var keepDate: [String] = []

    @IBOutlet weak var timeTextView: UITextView!
    @IBOutlet weak var dateText: HourDatePicker!
    @IBOutlet weak var calenderTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.calenderTableView.delegate = self
        self.calenderTableView.dataSource = self

        selectDate.tellCalenderText {[weak self] (titleText) in
            self?.bringDate(title: titleText)
        }


    }

    func bringDate(title: String){

        print("title: \(title)")
        self.keepDate.append(title)
        timeTextView.text.append(contentsOf: "\(title)\n")

    }

谢谢。

评论