'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 1:[1]
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
}
}()
Solution 2:[2]
If your app uses Keyboard at some time, then you can get Height of the Keyboard and apply that value to be the height of your DatePicker, otherwise you can say
datePickerHeight = view.frame.height / 3
to get a good appealing height. So if you use a bigger or smaller phone, it will do the maths by itself.
Solution 3:[3]
Just use sizeToFit
for calculate its own size:
let size = datePicker.sizeThatFits(.zero)
print("height:", size.height) // height: 315.0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Emptyless |
Solution 2 | Jeremy Caney |
Solution 3 | orakull |