Swift:如何在Swift中使用三个组件设置UIPickerView的默认值?

时间:2014-09-18 16:18:02

标签: swift uipickerview

如何在Swift中设置选择器视图的起始行? 我看到有一个Objective C的代码,但我不明白它。如果有人能解释我如何将Objective C代码翻译成Swift,那也很棒!

由于

5 个答案:

答案 0 :(得分:77)

这是我在其中一个应用中使用的代码:

// Declare the outlet to the picker in your storyboard
@IBOutlet var myPicker: UIPickerView!

//...

override func viewDidLoad() {
//...
    myPicker.selectRow(row, inComponent: 0, animated: true)
}

显然,将row0替换为您想要的任何值。

希望这有帮助!

答案 1 :(得分:12)

@IBOutlet weak var mPicker: UIPickerView!
var items: [String] = ["NoName1","NoName2","NoName3"] // Set through another ViewController
var itemAtDefaultPosition: String?  //Set through another ViewController

//..
//..

var defaultRowIndex = find(items,itemAtDefaultPosition!)
if(defaultRowIndex == nil) { defaultRowIndex = 0 }
mPicker.selectRow(defaultRowIndex!, inComponent: 0, animated: false)

答案 2 :(得分:0)

在swift 3中的pickerview中选择的默认值

如果你的阵列像下面那样

let pickerArray  = [
        ["displayValue":"--Select--" as AnyObject,"id":"" as AnyObject],
        ["displayValue":"Jame" as AnyObject,"id":"100" as AnyObject],
        ["displayValue":"Enamul" as AnyObject,"id":"201" as AnyObject]
    ]

只需在pickerview

中添加默认选择的波纹线
 pickerViewTextField.text  = pickerArray[0]["displayValue"] as! String

答案 3 :(得分:0)

SWIFT 5

函数“ SetDefaultValue”将通过在pickerData中找到用于填充选择器视图的项目位置,将pickerView定位在所需的字符串上。在此示例中,它将是“项目2”

var pickerView = UIPickerView()
var pickerData = ["item 1","item 2","item 3","item 4","item 5"]
var defaultItem = "item 2"

func setDefaultValue(item: String, inComponent: Int){
 if let indexPosition = pickerData.firstIndex(of: stepForwardRate){
   pickerView.selectRow(indexPosition, inComponent: inComponent, animated: true)   
 }
}

答案 4 :(得分:0)

试着把这行 myPicker.selectRow(row, inComponent: 0, animated: true) 在 覆盖 func viewDidAppear