简体   繁体   中英

Swift 4 - Setting selected Row in UIPickerView not working

I have a UIPickerView

@IBOutlet var professionText: UITextField!

let pickerView = UIPickerView()

var pickOption = Array<Dictionary<String, Any>>()

I am trying to get a selected row of my UIPickerView based off a condition

getProfession(){ result in

            self.pickOption = result

            var counter = 1

            for item in self.pickOption
            {

                if(item["id"] as! Int == self.userProfile["profession"] as! Int)
                {
                    print(counter)

                    self.pickerView.selectRow(counter, inComponent: 0, animated: false)
                }

                counter = counter + 1
            }

            self.professionText.text = self.pickOption[self.pickerView.selectedRow(inComponent: 0)]["text"] as? String

}

I did a bunch of prints in my condition and everything adds up

print(counter) //2
print(item["id"] as! Int) //2
print(item["text"] as! String) //Expected String
print(self.userProfile["profession"] as! Int) //2

What am I doing wrong?

I think your for-loop has some issues.

PS: You sure you need to start your counter from 1, and not from 0? If you're sure, I can edit my answer to include the initial count from 1.

Try this one:

for (index, item) in self.pickOption.enumerated() {

    if let id = item["id"] as? Int, let profession = self.userProfile["profession"] as? Int, id == profession {

        self.pickerView.selectRow(index, inComponent: 0, animated: false)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM