This lesson I want to show you how to create uipicker view in ios
And then create a new project with Command
–Shift-N project
fill in your name project:
This is work place:
After that you click here Main.story.board
we have to drag a uipickerview UIimageview and lableview on to View Controller:

Open the Assistant editor and control-drag from the picker
view and make an outlet named myPickerView
control-drag from the UIImageview and make an outlet named myImageview
control-drag from the Lableview and make an outlet named myLableview
Close Assitant editor
and go to the ViewController.swift file .Clean up the code then addthe data
for the "Uipickerview" like this
UIPickerView needs a delegate and a data source. In the viewDidLoad above we set both the
delegate and dataSource to to self so we can add the required methods here.
Change the class declaration to this:
Creating the Data
in line 13, we’re
declaring a new Array
instance variable to store the list of
data.By declaring it here as an instance variable. We can access this variable
form any method in this class and
variable will hold its value for the duration of the object lifetime.
Error:you have to add some required methods for the protocol
the two methods are in the data source .add these toward the bottom of your
code :
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView:
UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
return color.count
}
We have only one component for the picker view so we return
a literal 1. Using .count we get the number of rows from the data. We have some
optional methods to use in UIPickerViewDelegate. Add these below the Data
Source methods:
func pickerView(_ pickerView: UIPickerView,
titleForRow row: Int, forComponent component: Int) -> String? {
return color[row]
}
func pickerView(_ pickerView: UIPickerView,
didSelectRow row: Int, inComponent component: Int) {
myLable.text = color[row]
Detecting UIPickerView selected Row
First step is we have to add the datasource array as like below.
var uiColor = [UIColor.white,UIColor.red,UIColor.blue,UIColor.green,UIColor.gray]
we have to drag some picture on to project:
we have to add the datasource array as like below.
var imageview = ["g1.jpg","g2.jpg","g3.jpg","g4.jpg","g5.jpg"]
Note: g1 g2....it is name of picture
When selected UIPickerView row
the below delegate method will be called, here we have changed the background
color of uiview corresponding to the UIPickerView selected row values.
func pickerView(_ pickerView: UIPickerView,
didSelectRow row: Int, inComponent component: Int) {
myLable.text = color[row]
myImageview.image = UIImage(named: imageview[row])
self.view.backgroundColor = uicolor[row]








Comments
please post any question and comment right here so that i can support for you
Post a Comment