Teiki
Teiki

Reputation: 200

Make UIPickerView width fill the view

I'm new to iOS developement and I'm stuck with a graphical problem: I created a UIPickerView that appear above a google maps view. I would like to have the picker view width match the main view width. Currently, the picker is always taking 3/4 of the view and is locate on the top left angle:

the picker is not center and does not fill the view

I try to do that:

func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
    return self.view.bounds.width
}

But here is the result: The text inside picker is center but the picker does not fill the view

And here is what I would like to have: My goal Any idea? Is it possible to set this in the storyboard and not in swift?

Upvotes: 2

Views: 4909

Answers (2)

Olivier Wilkinson
Olivier Wilkinson

Reputation: 2856

Your problem is not the width of the components, self.view.bounds.width already fixed that, you have a layout issue.

Check your auto layout constraints for the picker view, you may have a fixed value width or height constraint if you automatically set the constraints using Xcode.

If you added the pickerView programmatically check that your frame has the same width as the view, or that the constraints are correct (see Sharat's answer)

Edit: code to programmatically set pickerView width -

//call this in viewDidLoad
func resizePickerViewToScreenWidth(){
     let oldFrame = airspacePicker.frame
     var newFrame = oldFrame
     newFrame.size.width = view.frame.size.width
     airspacePicker.frame = newFrame
}

Edit 2: code to programmatically create the pickerView

var airspacePicker: UIPickerView!

override func viewDidLoad() {
    super.viewDidLoad()
    createPickerView()
}

func createPickerView() {
    airspacePicker = UIPickerView(frame: CGRect(origin: CGPointZero, size: CGSize(width: view.frame.width, height: 220.0)))
    airspacePicker.backgroundColor = UIColor.blackColor()
    airspacePicker.autoresizingMask = .FlexibleWidth
    view.addSubview(airspacePicker)
}

Upvotes: 1

Sharat Kannan
Sharat Kannan

Reputation: 110

You can create the constraints for uipickerview. select the picker view and set the following constrains. You can set the constrains in the storyboard.

Trailing space:0 Leading Space :0 Botton Space:0

https://www.raywenderlich.com/115444/auto-layout-tutorial-in-ios-9-part-2-constraints

Upvotes: 2

Related Questions