2017-03-25 12 views
1

私はUIDatePickerを持っていて、自分のコードに基づいて、テーブルビューのセルが選択されるたびに日付ピッカーが再作成されるか、再作成されます。私はシングルトンと呼ばれるものを調べましたが、私は迅速に動くことができないので、彼らが仕事をするのは混乱しています。シングルトンはこの問題を防ぐことができますか?もしそうなら、私は自分のコードにどのように実装しますか?どうすればこの問題が発生しないようにすることができますか?ここで私はcreateDatePickerと関数createDatePickerを呼び出すために使用する機能のための私のコードは次のとおりです。UIDatePickerが複数回初期化されないようにする方法

let datePicker = UIDatePicker() 

func createDatePicker(indexPath: IndexPath, textField: UITextField){ 

    //Tool Bar 
    let toolbar = UIToolbar() 
    toolbar.sizeToFit() 

    //Bar Button Item 
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil) 
    toolbar.setItems([doneButton], animated: true) 

    textField.inputAccessoryView = toolbar 

    textField.inputView = datePicker 



} 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 


    if(indexPath.row != 0){ 

     let cell = tableView.cellForRow(at: indexPath) as! TableViewCell2 

     cell.textField.isUserInteractionEnabled = true 

     cell.textField.delegate = self 

     if(indexPath.row == 2 || indexPath.row == 3){ 

      createDatePicker(indexPath: indexPath, textField: cell.textField) 

     } 

     cell.textField.becomeFirstResponder() 


     if(indexPath.row == 1){ 

      cell.textField.placeholder = "Event Title" 

     } else if(indexPath.row == 2){ 

      cell.textField.placeholder = "Start Time" 

     } else if(indexPath.row == 3){ 


      cell.textField.placeholder = "End Time" 

     } 

    } 

} 

は、事前に任意の助けをありがとう!

+0

セルごとに別々の日付ピッカーが作成されるのはなぜですか? 'didSelect'メソッドの中にピッカーを作成する必要はありません。これはセル上のプロパティにすることができます。 – Sulthan

答えて

1

シングルトンは(あまりにも重いですが、多くの場合、再利用DateFormattersと同様、)正しい方法である:

class GlobalDatePicker: UIDatePicker { 
    static let shared = GlobalDatePicker() 
} 

あなたは、あなたのコード内で単一の日付ピッカーのインスタンスを使用します。

発信者がシングルトンを経由しないでインスタンスを作成できないようにするには、private init()を使用することもできます。

class GlobalDatePicker: UIDatePicker { 
    static let shared = GlobalDatePicker() 
    private init() {} 
    // Your methods that modify the picker here... 
} 

しかし、あなたはまた、あなたのコントローラでstatic variableを行うことができます。

static var datePicker: UIDatePicker = { 
    let picker = UIDatePicker() 
    picker.datePickerMode = .date 
    return picker 
}() 
0

あなただけのようなあなたのdatePickerは、静的にすることができます。

static let datePicker = UIDatePicker() 

次に、あなたが通過する必要はありません。シングルトン。しかし、シングルトンが必要な場合はthis questionに行きます。ここでシングルトンの振る舞いを持つ方法は複数あります。Swift-3

関連する問題