gpt4 book ai didi

xcode - 如何在一个 View Controller 中使用两个 UIPickerViews?

转载 作者:IT王子 更新时间:2023-10-29 05:06:57 27 4
gpt4 key购买 nike

我在一个 View Controller 中有两个 UIPickerController。我可以让一个工作,但是当我添加第二个时,我的应用程序崩溃了。这是我用于一个选择器 View 的代码:

import UIKit

class RegisterJobPosition: UIViewController, UIPickerViewDelegate {

@IBOutlet weak var positionLabel: UILabel!

var position = ["Lifeguard", "Instructor", "Supervisor"]

override func viewDidLoad() {
super.viewDidLoad()
}

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

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

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

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
positionLabel.text = position[row]
}
}

现在,我怎样才能让第二个拣货员工作呢?假设我的第二个选择器 View 称为 location(另一个称为 position)。我尝试在 location 的选择器 View 方法中复制代码,但它不起作用。

最佳答案

这是我的解决方案:

  • 在 Storyboard中,将两个 UIPickerView 实例添加到您的 View
  • 在“属性检查器”下将第一个选择器的标签设置为1,将第二个选择器设置为2
  • control + 从每个选择器拖动到顶部黄色 View Controller 图标并选择 dataSource。重复相同的选择 delegate
  • UIPickerViewDataSourceUIPickerViewDelegate 添加到您的 View Controller :

    class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
  • 在您的 View Controller 类中,为选择器创建空数组:

    var picker1Options = []
    var picker2Options = []
  • viewDidLoad() 中,用您的内容填充数组:

    picker1Options = ["Option 1","Option 2","Option 3","Option 4","Option 5"]
    picker2Options = ["Item 1","Item 2","Item 3","Item 4","Item 5"]
  • 实现委托(delegate)和数据源方法:

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

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if pickerView.tag == 1 {
    return picker1Options.count
    } else {
    return picker2Options.count
    }
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    if pickerView.tag == 1 {
    return "\(picker1Options[row])"
    } else {
    return "\(picker2Options[row])"
    }
    }

关于xcode - 如何在一个 View Controller 中使用两个 UIPickerViews?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642164/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com