Search code examples
swiftsprite-kituitextfielduipickerview

UIPickerView in SpriteKit


I'm adding a UIPickerView into a SpriteKit scene. The code looks like this:

import UIKit
import SpriteKit

class MyScene: SKScene, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
    let myField = UITextField(frame: CGRectMake(UIScreen.mainScreen().bounds.size.width * 0.4, UIScreen.mainScreen().bounds.size.height * 0.35, 200, 30))
    let myPickOptions = ["One", "Two", "Three"]

    override func didMoveToView(view: SKView) {
        super.didMoveToView(view)
        let myPickerView  : UIPickerView = UIPickerView()
        myField.inputView = genderPickerView
        myField.font = UIFont.systemFontOfSize(15)
        myField.borderStyle = UITextBorderStyle.RoundedRect
        myPickerView.dataSource = self
        myField.delegate = self
        self.view!.addSubview(myField)
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
        return 1
    }

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

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return myPickOptions[row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        myField.text = "\(myPickOptions[row])"
    }

The picker appears on the screen when I tap inside the textField but without data (just some question marks in the picker).

Any idea what's wrong?

ADDITIONAL EDIT: When I take a look at the two data source methods, I see the count of number of rows being correctly returned, although it's being returned 28 times. Maybe that's normal but it looks strange. When I look into the delegate methods, it looks like the first one isn't being called at all (no row data being returned).

AND SOLVED IT... I needed to add a second delegate:

myPickerView.delegate = self

Solution

  • I missed the second delegate.. all good when it's added