无法选择pickerView的默认值

时间:2017-07-30 13:33:44

标签: swift uipickerview

我有一个pickerView,其中有很多主题。每个科目都是这样的一个班级:

GET https://my_url.aspx?
callback=jQuery32103473…
age%20School&address=Ruby&website=www.hs.com&twitter=%23hs&_=1501421197069 
send @ jquery-3.2.1.min.js:4
ajax @ jquery-3.2.1.min.js:4
(anonymous) @ magic.js:20
dispatch @ jquery-3.2.1.min.js:3
q.handle @ jquery-3.2.1.min.js:3

我以这种方式设置我的pickerView:

class subjects {
    var idSubject: String = "";
    var nameSubject: String = "";
    var notesSubject: String = "";
    var colorSubject: String = "";

    init(subjectId: String, subjectName: String, subjectNotes: String, subjectColor: String) {
        idSubject = subjectId
        nameSubject = subjectName
        notesSubject = subjectNotes
        colorSubject = subjectColor
    }

    func printSubject(){
        print(idSubject," - ",nameSubject," - ",notesSubject," - ",colorSubject)
    } 
}

我想选择一个特定主题的行,但我不能因为public func numberOfComponents(in pickerView: UIPickerView) -> Int{ return 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ return MenuViewController.subjectsArray.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { self.view.endEditing(true) return MenuViewController.subjectsArray[row].nameSubject } 它“无法将类型'String'的值转换为预期的参数类型'(主题)抛出 - > Bool' “在这行代码中:

indexOf

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

if let index = MenuViewController.subjectsArray.index(where: {
    $0.nameSubject == "Matematica"
}) {
    self.subjectsMenu.selectRow(index, inComponent: 0, animated: true)
}

答案 1 :(得分:1)

而不是使用index(of:),这种情况的适当方法是index(where:)

  

返回集合元素的第一个索引   满足给定的谓词

这是适用的,因为您有一个自定义对象数组(subjects),如下所示:

if let index = MenuViewController.subjectsArray.index(where: { (subjectsObject) -> Bool in
    subjectsObject.nameSubject == "Matematica"
}) {
    print("found the desired index: \(index)")
    self.subjectsMenu.selectRow(index, inComponent: 0, animated: true)
}

补充说明:

  • 自定义类的名称应为“Subject”而不是“subject”。通常,类的名称引用单个对象,upper camel case

  • 比较字符串:subjectsObject.nameSubject == "Matematica"时,最好修剪并比较其 lower / upper 案例版本,如下所示:

    subjectsObject.nameSubject.lowercased().trimmingCharacters(in: .whitespaces) == "Matematica".lowercased().trimmingCharacters(in: .whitespaces)