Reputation: 200
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:
I try to do that:
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return self.view.bounds.width
}
And here is what I would like to have:
Any idea? Is it possible to set this in the storyboard and not in swift?
Upvotes: 2
Views: 4909
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
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