Swift 4 selectRow для pickerView не работает в viewDidAppear - PullRequest
0 голосов
/ 28 ноября 2018

Я использую UIPickerView, и он вызывается нажатием кнопки, например, так:

@IBAction func communityButtonPressed(_ sender: Any) {
    //Set the picker view delegate to self
    pickerView.delegate = self

    //Set the picker view data source to self
    pickerView.dataSource = self

    //Define the tool bar
    let toolBar = UIToolbar()

    //Set tool bar style
    toolBar.barStyle = UIBarStyle.default

    //Set tool bar translucent to true
    toolBar.isTranslucent = true

    //Resizes and moves the tool bar view so it just encloses its subviews.
    toolBar.sizeToFit()

    //Define done button for tool bar
    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(Dashboard.donePicker))

    //Define space inbetween the buttons for tool bar
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)

    //Define cancel button for tool bar
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(Dashboard.cancelPicker))

    //Assign tool bar buttons to tool bar
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)

    //Set the tool bar to be interactive
    toolBar.isUserInteractionEnabled = true

    //Add the tool bar to the picker view
    pickTextField.inputAccessoryView = toolBar

    //Add picker view to view
    view.addSubview(pickTextField)

    //Assign the picker view to picker text field
    pickTextField.inputView = pickerView

    //Set picker text field as first responder
    pickTextField.becomeFirstResponder()
}

Теперь я пытаюсь установить выбранную строку в viewDidAppear, но она не устанавливает выбранную строку.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    //Call method to get the user bundle settings
    registerSettingsBundle()

    //Apply the users bundle settings
    updateDisplayFromDefaults()

    //Clear the picker options
    pickOption = [String]()

    //For each community in the app delegate community array
    for item in (appDelegate.communityDescriptionArray?["kCommunityDescriptions"] as! [AnyObject])
    {
        //Add it to the picker options
        pickOption?.append(item as! String)
    }

    self.selectedIndex = (appDelegate.communityDescriptionArray?["kCommunityDescriptions"]!.index(of: UserDefaults.standard.string(forKey: "community")!))!

    self.pickerView.selectRow(3, inComponent: 0, animated: true)
}

Я заметил, что сначала загружается viewDidAppear, затем numberOfRowsInComponent, затем titleForRow, поэтому выбранная строка не принимает?

...