Search code examples
iosswift3uipickerview

How can i change Uipickerview position?


This is the storyboard

enter image description here

I create a picker view like that ;

    pickerView = UIPickerView()
    pickerView.center = view.center
    view.addSubview(pickerView)
    pickerView.dataSource = self
    pickerView.delegate = self

When i run the app picker view show up like that . enter image description here

But i want the change position pickerview.How can i do that ?


Solution

  • If you add something programmatically(calling addSubView:) you have to do autolayout programmatically in order to position your view in correct order.

    There are lots of tutorials about this.I am just giving you some example about it.Suppose if you want to put your PickerView

    Left position : 20px
    
    Top position : 100px
    

    You have to first write below line.Why? just google it. :)

    pickerView.translatesAutoresizingMaskIntoConstraints = false
    

    I am using anchoring.Because code is very much reduced.Thanks to Apple.

     pickerView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20.0).isActive = true
     pickerView.topAnchor.constraint(equalTo:self.view.topAnchor, constant: 100.0).isActive = true
    

    Of course you must add this after you add subView. remove this line from your code by the way.You can center align using autolayout. :)

    pickerView.center = view.center