从NSArray使用UIPicker获取titleForRow - Swift

时间:2014-08-14 14:59:00

标签: ios swift nsarray uipicker

我尝试使用下面的UIPickerViewDelegate从我的数组中返回对象:

var myArr = NSArray()

将对象添加到我的数组

self.myArray = NSArray(objects: "Mr", "Mrs", "Miss", "Ms", "Dr", "Master", "Rev",
            "Fr", "Atty", "Prof", "Hon")

这是我的代表

func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
    var string = NSString(coder: self.myArray.objectAtIndex(row) as NSCoder)
    return string
}

然而,这引发了一个例外。我该怎么做这个简单的任务?

1 个答案:

答案 0 :(得分:4)

完全基于你的问题,并假设你没有提到任何相关内容,摆脱编码器的东西:

func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
    return self.myArray.objectAtIndex(row) as NSString
}

由于这是一个快速的程序,你也可能不会使用NSArray,因为这会导致类型模糊:

var myArr = ["Mr", "Mrs", "Miss", "Ms", "Dr", "Master", "Rev",
        "Fr", "Atty", "Prof", "Hon"]

现在你的委托方法变得更加清晰:

func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
    return myArray[row]
}