UIPickerView 行文本被隐藏

UIPickerView row text is hidden

我相信我已经按照步骤实现了 UIPickerView 来显示字符串数组。由于某种原因,titleForRow 中的文本被隐藏了。我似乎选择器视图正在获取数组计数,因为我可以滚动。如果名字,我只是无法获得列表。我正在使用 UIStoryboard 并且所有插座都已连接。任何帮助将不胜感激。

extension SongPlayerViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

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

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

//when user selects row
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
    }
 }
  class SongPlayerViewController: UIViewController {
     
         let hertzArray = ["432Hz", "528Hz", "174Hz", "396Hz", "417Hz", "639Hz", "741Hz", "852Hz"]

         @IBOutlet weak var pickerView: UIPickerView!
         @IBOutlet weak var toolBar: UIToolbar!

          //when view did load
          override func viewDidLoad() {
          super.viewDidLoad()

              pickerView.dataSource = self
              pickerView.delegate = self
          
          }
     }

我认为您发布的代码没有问题。我用一些设置代码把它放到了 playground 中,它就可以工作了。您应该检查 nib 文件中的插座并在运行时检查以确保 pickerView 属性 被分配。按照评论中的建议,使用视图调试工具检查选择器的尺寸

(https://developer.apple.com/library/archive/documentation/ToolsLanguages/Conceptual/Xcode_Overview/ExaminingtheViewHierarchy.html)

这是我正在使用的 Playground:

导入 UIKit 导入 PlaygroundSupport

class SongPlayerViewController: UIViewController {
    let hertzArray = ["432Hz", "528Hz", "174Hz", "396Hz", "417Hz", "639Hz", "741Hz", "852Hz"]

    @IBOutlet weak var pickerView: UIPickerView!

    override func loadView() {
        let pickerView = UIPickerView()
        self.pickerView = pickerView

        view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
        view.addSubview(pickerView)

        pickerView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        pickerView.dataSource = self
        pickerView.delegate = self
    }
}


extension SongPlayerViewController: UIPickerViewDataSource, UIPickerViewDelegate {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

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

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

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    }
}

let songController = SongPlayerViewController()
PlaygroundSupport.PlaygroundPage.current.liveView = songController