UIPickerView上显示的问号,而不是Xcode 10上的领域数据

时间:2018-09-29 16:10:06

标签: ios swift realm uipickerview

我正在学习从Realm数据库填充UIPickerView。

问题是UIPickerView显示“?”而不是数据。

这是我的代码:

import UIKit
import RealmSwift

class AjouterEmpruntViewController: UIViewController,    UIPickerViewDelegate, UIPickerViewDataSource {
    @IBOutlet weak var PickerViewListeAmis: UIPickerView!

    /* Initialisation de Realm */
    let realm = try! Realm()

    var data:Results<Ami>!
    var listOfFriends:[Ami] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        /* Definition des sources du PickerView */
        self.PickerViewListeAmis.dataSource = self
        self.PickerViewListeAmis.delegate = self

        /* Constitution de la liste de pseudos d'amis pour alimenter le PickerView  */
        self.data = realm.objects(Ami.self)
        self.listOfFriends = Array(self.data)
    }

    @IBAction func btnSaveEmprunt(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true)
    }

    @IBAction func btnCancelEmprunt(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return listOfFriends.count
    }

    private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        print("pseudo = "+listOfFriends[row].pseudo)
        return listOfFriends[row].pseudo
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        print("selected Ami is "+listOfFriends[row].pseudo)
    }
}

我遵循了本教程http://sourcefreeze.com/ios-uipickerview-example-using-swift/

能帮我解决问题吗?

结果如下: 问题?代替数据 1

1 个答案:

答案 0 :(得分:0)

您的titleForRow方法签名错误,因此不会被调用。

它必须是:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?

不是:

private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?

删除private并添加缺少的_