Serhii Didanov
Serhii Didanov

Reputation: 2338

UIPickerView width constraint issue

I need to add UIPickerView to UIAlertController. I use code:

let alertView = UIAlertController()
let pickerView = UIPickerView()
pickerView.translatesAutoresizingMaskIntoConstraints = false

alertView.view.addSubview(pickerView)
pickerView.topAnchor.constraint(equalTo: alertView.view.topAnchor, constant: 50).isActive = true
pickerView.bottomAnchor.constraint(equalTo: alertView.view.bottomAnchor, constant: -50).isActive = true
pickerView.centerXAnchor.constraint(equalTo: alertView.view.centerXAnchor).isActive = true
pickerView.widthAnchor.constraint(equalTo: alertView.view.widthAnchor).isActive = true

present(alertView, animated: true)

Here it is a result:

enter image description here

Why width of the UIPickerView more than UIAlertController?

Also I tried:

pickerView.widthAnchor.constraint(equalTo: alertView.view.widthAnchor, multiplier: 0.5).isActive = true

But got the same result...

Upvotes: 0

Views: 146

Answers (1)

V D Purohit
V D Purohit

Reputation: 1189

when you give a constraint of width which exactly doing right.Issue is from your side look below image when you give a width constant of alertview.view which one UIalertController's main view.For better understand look below image(last view behind blue colour view colour and PickerView color is red.).

enter image description here

Now,we show actual alerview which one subview of main view(in above image Blue colour with Ok button). change width constraint with subview instead of main view like:-

For better under standing:-

for view in alertView.view.subviews {
        print(view)
       //just add color which is shown in bellow image.
        view.backgroundColor = UIColor.blue
    }

So, Solution is like:-

pickerView.widthAnchor.constraint(equalTo: alertView.view.subviews[0].widthAnchor).isActive = true

Result:-

enter image description here

I hope this help you, Thanks

Upvotes: 1

Related Questions