UIPickerView Width in iOS8 Swift

2019-04-11 15:56发布

问题:

I simply can not find out how to get a width of a component on my UIPickerView. It's not allowing something simple (Int) as it needs to be CGFloat. What exactly do I put in the <#code#> section?

func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
    <#code#>
}

Thank you!

回答1:

That method doesn't "get a width of a component..." The picker view calls that method to ask you how wide a component should be.

Your method could be as simple as:

func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat 
{
  return CGFloat(25.0)
}

(or whatever width is appropriate for your picker view...)

You just need to cast the result to the exptected type.



回答2:

The best way to return a width of a component is to use bounds.width:

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

Where x would be a number of the components you desire to have in a PickerView.