How can i change Uipickerview position?

2019-07-13 20:49发布

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 ?

2条回答
老娘就宠你
2楼-- · 2019-07-13 21:17

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
查看更多
Animai°情兽
3楼-- · 2019-07-13 21:39

You have to set layout constraint to change the position of pickerview as per your requirements.

if you set the below line it will show center of the view

pickerView.center = view.center

you have to set the constraint value in respect of superview or as your required position.

How to add constraint from storyboard

查看更多
登录 后发表回答