如何在UIPickerView中将第一个条目设为空白

时间:2016-08-16 20:19:57

标签: ios swift

我尝试为此找到一个示例,但所有半相关示例似乎都使用UIPickerView的静态数据,这并不适合我的情况。

我有一个UIPickerView对象从数据库中获取数据(本例中为核心数据) - 选择器与文本字段相关联。目标是能够从选择器中选择现有条目,或者能够创建一个新条目,该条目将在下次运行应用程序时添加到选取器中。一般情况下,这一切都正常 - 除了一部分:当应用程序首次加载时,文本字段为空(所需),但选择器视图显示选择的第一个现有值( < em>不 期望

如何在数据库中没有这样的条目的情况下在选择器的开头添加空白条目?

我尝试将以下内容添加到viewDidLoad(),但它似乎没有任何区别:

picker.selectRow(-1, inComponent: 0, animated: false)

2 个答案:

答案 0 :(得分:3)

尝试这样的事情:

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    let entries = ["First", "Second", "Third"]

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return entries.count + 1 // +1 for the empty entry
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return row == 0 ? "" : entries[row - 1]
    }

}

答案 1 :(得分:0)

感谢Andre - 结果代码工作(我摆脱了picker.selectRow(-1, inComponent: 0, animated: false)):

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    let rows = _getNumDataRows() // I had reasons for pulling this out
    return rows + 1 // <<<=== MODIFIED AS PER SUGGESTION
}

func _getNumDataRows() -> Int {
    let entityDescription = NSEntityDescription.entityForName("Contacts", inManagedObjectContext: managedObjectContext)

    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let results = try managedObjectContext.executeFetchRequest(request)
        return results.count
    }
    catch let error as NSError {
        status.text = error.localizedFailureReason
    }
    print("UNABLE TO FIND ROWS")
    return 0
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return row == 0 ? "" : _getSelectedValue(row - 1) // <<<=== MODIFIED AS PER SUGGESTION
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    name.text = row == 0 ? "" : _getSelectedValue(row - 1) // <<<=== MODIFIED AS PER SUGGESTION
}

func _getSelectedValue(row: Int) -> String {
    print("Selected Row: \(row)")
    let entityDescription = NSEntityDescription.entityForName("Contacts", inManagedObjectContext: managedObjectContext)

    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let results = try managedObjectContext.executeFetchRequest(request)
        return results[row].valueForKey("name") as! String
    }
    catch let error as NSError {
        status.text = error.localizedFailureReason
    }
    print("NO RECORDS FOUND")
    return ""

}