Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Tạo UIPickerView từ mảng theo chương trình trong iOS

Tạo UIPickerView hoàn toàn bằng code (không dùng Storyboard):

  1. Tạo UIPickerView(), set delegate, dataSource, add subview, căn giữa.
  2. ViewController conform UIPickerViewDelegate, UIPickerViewDataSource.
  3. Mảng dữ liệu: let dataArray = ["English","Maths","History","German","Science"].
  4. Implement 3 method bắt buộc: numberOfComponents, numberOfRowsInComponent, titleForRow.
func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return dataArray.count }
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return dataArray[row] }