Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

ios - How do I use multiple picker views with different data sources in the same view?

I have a view with three picker views in it. Two of the picker views have the same data, an array with the numbers 1 to 100. The third picker view has an array with a list of model railroad track manufacturers in it. I have tagged the picker views using a method I found on this site, but when I run the app, all three picker views have 1 to 100 as their data. I also control-dragged from all picker views to the yellow circle at the top of the view and clicked dataSource and delegate. How do I use multiple picker views with different data sources in one view? Also, in order to make the code run, I had to delete weak from all @IBOutlet statements relating to the picker views. Is this a bad thing to do? I am relatively new to code. Thanks.

Picker View Scene Screen Shot

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    //MARK: Properties

    @IBOutlet var layoutLengthPickerView: UIPickerView!
    @IBOutlet var layoutWidthPickerView: UIPickerView!
    @IBOutlet var trackPickerView: UIPickerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        layoutLengthPickerView = UIPickerView()
        layoutWidthPickerView = UIPickerView()
        trackPickerView = UIPickerView()

        layoutLengthPickerView.tag = 0
        layoutWidthPickerView.tag = 1
        trackPickerView.tag = 2
    }

    let numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]

    let manufacturers = ["Atlas True Track", "Atlas Code 100", "Atlas Code 83", "Bachmann Nickel Silver", "Bachmann Steel Alloy", "Kato", "Life-Like Trains Code 100", "LIfe-Like Trains Power-Loc", "Peco Code 100", "Peco Code 83", "Peco Code 75", "Shinohara Code 100", "Shinohara Code 70", "Walthers"]

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

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return numbers[row]
        } else if pickerView.tag == 1 {
            return numbers[row]
        } else if pickerView.tag == 2 {
            return manufacturers[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return numbers.count
        } else if pickerView.tag == 1 {
            return numbers.count
        } else if pickerView.tag == 2 {
            return manufacturers.count
        }
        return 1
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When dealing with multiple controls with delegates and data sources, you should consider avoiding view controller bloat (i.e., in the spirit of the single responsibility principle) by creating separate objects for the delegates of the multiple pickers. This keeps this logic out of the view controller, itself, and avoids single cumbersome UIPickerViewDataSource and UIPickerViewDelegate methods trying to service multiple pickers with hairy if-else or switch statements.

For example, here is a view controller that has outlets for two pickers, but rather than encumbering the view controller with code to manage the dataSource and delegate for these pickers, you can have separate objects for each picker, and all the view controller has to do is to say which delegate object will handle which picker:

class ViewController: UIViewController {

    @IBOutlet weak var namePicker: UIPickerView!
    @IBOutlet weak var numberPicker: UIPickerView!

    let namePickerDelegate = NamePickerDelegate()
    let numberPickerDelegate = NumberPickerDelegate()

    override func viewDidLoad() {
        super.viewDidLoad()

        namePicker.delegate = namePickerDelegate
        namePicker.dataSource = namePickerDelegate

        numberPicker.delegate = numberPickerDelegate
        numberPicker.dataSource = numberPickerDelegate
    }

    @IBAction func didTapButton(_ sender: Any) {
        let nameValue = namePicker.selectedRow(inComponent: 0)
        let numberValue = numberPicker.selectedRow(inComponent: 0)

        print("(nameValue); (numberValue)")
    }

}

The only trick is to make sure to keep a strong reference to those delegate objects, as shown above, because the picker, itself, only has weak references to its delegate, as is best practice.

And the implementation of the picker delegate methods is much cleaner:

class NamePickerDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
    let names = ["Mo", "Larry", "Curley"]

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

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

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

class NumberPickerDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
    let numbers: [String] = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return (0 ..< 100).compactMap { formatter.string(for: $0) }  // use `flatMap` in Xcode versions prior to 9.3
    }()

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

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

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

Now, this is still, obviously, a simplified example, but the beauty is that as the code gets more complicated, the details are encapsulated within separate objects, rather than encumbering a single view controller with all the code.


If you want, you can have the view controller provide the list of strings to the delegate/data source object. In fact, that simplifies it because you need only one class for the picker delegate, and you just instantiate a different one for each picker:

class ViewController: UIViewController {

    let names = ["Mo", "Larry", "Curley"]

    let numbers: [String] = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return (0 ..< 100).compactMap { formatter.string(for: $0) }  // use `flatMap` in Xcode versions prior to 9.3
    }()

    @IBOutlet weak var numberPickerOne: UIPickerView!
    @IBOutlet weak var numberPickerTwo: UIPickerView!
    @IBOutlet weak var namePicker: UIPickerView!

    lazy var numberPickerOneDelegate: PickerDelegate = PickerDelegate(strings: self.numbers)
    lazy var numberPickerTwoDelegate: PickerDelegate = PickerDelegate(strings: self.numbers)
    lazy var namePickerDelegate:PickerDelegate = PickerDelegate(strings: self.names)

    override func viewDidLoad() {
        super.viewDidLoad()

        numberPickerOne.delegate   = numberPickerOneDelegate
        numberPickerOne.dataSource = numberPickerOneDelegate

        numberPickerTwo.delegate   = numberPickerTwoDelegate
        numberPickerTwo.dataSource = numberPickerTwoDelegate

        namePicker.delegate        = namePickerDelegate
        namePicker.dataSource      = namePickerDelegate
    }

}

class PickerDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
    let strings: [String]

    init(strings: [String]) {
        self.strings = strings
        super.init()
    }

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...