swiftuidatepicker

How to set the correct height for a UIDatePicker?


How do I set the height of a datePicker correctly across the range of different iOS devices? I can get the width from the width of the window but not the height.

Here's my code:

let origin = CGPoint(x: 0, y: 0)
let width = app_delegate.window!.frame.width
let size = CGSize(width: width, height: 300)
let frame = CGRect(origin:origin , size: size)
birthday.inputView = UIDatePicker(frame: frame)

Solution

  • I think you are confusing Bounds and Frame. Frame is a rectangle describing the superview. Bounds is that of the local rectangle.

    If you want the height and width of the device's screen you need to use the bounds of:

    let screenSize = UIScreen.main.bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height
    

    If you want the height to be a maximum of 300 (as in your example) you can use a computed variable like:

    let height : CGFloat = {
        if size.height > 300.0 {
            return 300.0
        } else {
            return size.height
        }
    }()