在Swift中设置UIPickerView的默认值?

smdnsysy  于 2022-12-26  发布在  Swift
关注(0)|答案(5)|浏览(167)

如何在Swift中设置选择器视图的起始行?
我看到there is a similar question for Objective-C,但不理解代码。

5sxhfpxr

5sxhfpxr1#

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

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

//...

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

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

kkbh8khc

kkbh8khc2#

@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)
osh3o9ms

osh3o9ms3#

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: item){
   pickerView.selectRow(indexPosition, inComponent: inComponent, animated: true)   
 }
}
9rnv2umw

9rnv2umw4#

尝试将该行myPicker.selectRow(row, inComponent: 0, animated: true)放入覆盖函数视图DidAppear中

7eumitmz

7eumitmz5#

在swift 3的选择器视图中选择默认值
如果你的阵列像风箱

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]
    ]

只需为选择视图中选定的默认值添加以下行

pickerViewTextField.text  = pickerArray[0]["displayValue"] as! String

相关问题