【问题标题】:Can't select default value of pickerView无法选择pickerView的默认值
【发布时间】:2018-01-06 02:36:58
【问题描述】:

我有一个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)
    } 
}

我这样设置我的pickerView:

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
}

我想选择特定主题的行,但我不能因为indexOf 它“无法将'String'类型的值转换为预期的参数类型'(subjects) throws -> Bool'”代码行数:

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

有人可以帮我吗?

【问题讨论】:

  • subjectsArray 数组的类型是什么?是subjects ([subjects]) 的数组吗?

标签: swift uipickerview


【解决方案1】:
if let index = MenuViewController.subjectsArray.index(where: {
    $0.nameSubject == "Matematica"
}) {
    self.subjectsMenu.selectRow(index, inComponent: 0, animated: true)
}

【讨论】:

  • 我要写什么而不是YourSubjectType?
  • @Marco YourSubjectType 表示代表主题的类型名称。对于您的问题,这意味着subjects
  • 在这种情况下,如果作为闭包参数提及,则无需强制转换,可以按原样使用;检查我的答案,让你更清楚:)
  • @AhmadF 是的,我编辑了答案并删除了演员表
【解决方案2】:

不使用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" 而不是 "subjects"。通常,类的名称是指一个单一的对象,upper camel case

  • 比较字符串时:subjectsObject.nameSubject == "Matematica",最好修剪并比较它的小写/大写版本,如下:

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

【讨论】:

    猜你喜欢
    • 2011-11-18
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多