UIPickerView和CoreData数组

时间:2017-10-08 23:18:15

标签: swift core-data uipickerview

在这里看不到我的错误。我正在从CoreData获取记录到Array并且无法在UIPickerView中显示所有记录。我确信我错过了一些非常简单的东西,但刚开始学习Swift并寻找一些指导。

预期结果:我的获取请求中有2个玩家,两个玩家都应该出现在UIPickerView中

实际结果:只显示一条记录

代码:

import UIKit
import CoreData

class selectPlayersStatsViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, NSFetchedResultsControllerDelegate {

@IBOutlet weak var playerSelector: UIPickerView!

var moc:NSManagedObjectContext!

var playerPickerSource: [String] = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    playerSelector.dataSource = self
    playerSelector.delegate = self

    moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let playerIsRequest:NSFetchRequest<PlayerTable> = PlayerTable.fetchRequest()
        playerIsRequest.returnsObjectsAsFaults = false

    var playerArray = [PlayerTable]()

    do {
        playerArray = try moc.fetch(playerIsRequest)

    } catch {
        print(error)
    }

   for player in playerArray {

        playerPickerSource = [player.playername!]
        //print(playerPickerSource)
        //print(playerPickerSource.count)
    }
}


//PICKER VIEW
public func numberOfComponents(in pickerView: UIPickerView) -> Int{
    return 1

}

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

    return playerPickerSource.count

}

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

    return playerPickerSource[row]

}

public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let playerLabel = UILabel()
    let playerData = playerPickerSource[row]

    let myTitleYear = NSAttributedString(string: playerData, attributes: [NSFontAttributeName:UIFont(name: "Avenir Next", size: 18.0)!,NSForegroundColorAttributeName:UIColor.black])

    playerLabel.textAlignment = .center
    playerLabel.attributedText = myTitleYear
    return playerLabel

}
/////////
@IBAction func goViewButton(_ sender: Any) {

    let myPlayer = playerPickerSource[playerSelector.selectedRow(inComponent: 0)]
    //let myYear = yearPickerSource[playerSelector.selectedRow(inComponent: 0)]
    print(myPlayer)
   // print(myYear)

}
}

1 个答案:

答案 0 :(得分:1)

似乎你在循环中每回合为playerPickerSource分配一个新数组。

所以而不是

for player in playerArray {

    playerPickerSource = [player.playername!]
    //print(playerPickerSource)
    //print(playerPickerSource.count)
}

你应该试试

for player in playerArray {
    playerPickerSource.append(player.playername!)
}