线程1:致命错误:迅速4索引超出范围

时间:2018-12-04 07:14:19

标签: ios swift

我的代码中存在线程1致命错误的问题。我尝试在一个视图控制器中创建2个选择器。但是错误不断出现。当我尝试在手机上运行时,在此页面之前一切正常(选择器无法移动)。它在从底部开始的第6行显示(返回主题[行])错误

enter image description here

这里是我的代码:

Import UIKit

class ThirdViewController: UIViewController, UIPickerViewDelegate, 
UIPickerViewDataSource {



@IBOutlet weak var classPickerView: UIPickerView!
@IBOutlet weak var subjectPickerView: UIPickerView!
@IBOutlet weak var nextButton: UIButton!


let subclass = ["AA234", "ASA231", "AA9292", "AAA839", "AA5682", "AAA789"]
let subject = ["Introduction to Database","Introduction to Programming","Mathematics","Multimedia"]



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

@IBAction func buttonPressed(_ sender: Any) {

    let picker = UIImagePickerController()
    picker.delegate = (self as! UIImagePickerControllerDelegate & UINavigationControllerDelegate)

    //select row first
    let selectedRow1 = classPickerView.selectedRow(inComponent: 0)
    let selectedRow2 = subjectPickerView.selectedRow(inComponent: 0)


    let selectedClass = subclass [selectedRow1]
    let selectedSubClass = subject [selectedRow2]


    let messageToShow = "Class \(selectedClass) with the subject \(selectedSubClass)"

    // insert  messageToShow in message to appear what u selected
    let actionSheet = UIAlertController (title: "Please Confirm Before Scan", message: messageToShow, preferredStyle: .alert)
    let okAction = UIAlertAction (title: "Proceed to Scan", style: .default, handler: nil) //{action in
        //picker.sourceType = .camera})

    let cancelAction = UIAlertAction (title: "Cancel", style: .cancel, handler: nil)
    actionSheet.addAction(okAction)
    actionSheet.addAction(cancelAction)

    present(actionSheet, animated: true, completion: nil)



}

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
     if (pickerView.tag == 1) {
        return subject.count

    }
    else {
        return subclass.count
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {
        return subject[row]
    }
    else {
        return subclass[row]
    }
 }

}

1 个答案:

答案 0 :(得分:2)

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
     if (component == 0) {
        return subject.count
    }
    else {
        return subclass.count
    }
}

如上所述更改numberOfRowsInComponent代码