how to change font size using autolayout for different iPhone sizes like iPhone 5, 5s, 8 having different font size for labels, textfields.
Asked
Active
Viewed 531 times
0
-
Using auto shrink will only change particular label not all fonts of particular screen. – Meetesh Singh May 18 '18 at 07:26
2 Answers
0
You can do that using Size classes. The idea is that you can display UI elements a bit differently or anyway you like on different devices. This would enable you to change font properties for certain devices the way you like.
There are a lot of good tutorials on the web and also the official documentation, which you can find here: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/Size-ClassSpecificLayout.html
ZassX
- 1,369
- 2
- 14
- 35
0
Following UIDevice extension may help you (I do not suggest to use, such kind of code behavior. You need to update it everytime, with launch of new device, that does not match with existing screen size.):
extension UIDevice {
enum DeviceType: String {
case iPhone4_4S = "iPhone 4 or iPhone 4S"
case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE"
case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6S, iPhone 7 or iPhone 8"
case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus or iPhone 8 Plus"
case iPhoneX = "iPhone X"
case unknown = "iPadOrUnknown"
}
var deviceType: DeviceType {
switch UIScreen.main.nativeBounds.height {
case 960:
return .iPhone4_4S
case 1136:
return .iPhones_5_5s_5c_SE
case 1334:
return .iPhones_6_6s_7_8
case 1920, 2208:
return .iPhones_6Plus_6sPlus_7Plus_8Plus
case 2436:
return .iPhoneX
default:
return .unknown
}
}
}
// Get device type (with help of above extension) and assign font size accordingly.
let label = UILabel()
let deviceType = UIDevice.current.deviceType
switch deviceType {
case .iPhone4_4S:
label.font = UIFont.systemFont(ofSize: 10)
case .iPhones_5_5s_5c_SE:
label.font = UIFont.systemFont(ofSize: 12)
case .iPhones_6_6s_7_8:
label.font = UIFont.systemFont(ofSize: 14)
case .iPhones_6Plus_6sPlus_7Plus_8Plus:
label.font = UIFont.systemFont(ofSize: 16)
case .iPhoneX:
label.font = UIFont.systemFont(ofSize: 18)
default:
print("iPad or Unkown device")
label.font = UIFont.systemFont(ofSize: 20)
}
Krunal
- 77,632
- 48
- 245
- 261
-
@Moritz - you may be right, half of the solution is duplicate. But in that question OP wanted to set font from Storyboard (interface builder) but the same was not possible So I suggested him to do it programmatically. And in this question OP wants the same result programatically. Generally I've seen solution requested for interface builder and programatically are considered as different on SO. And I was confused between this situation, so I did not mark this as duplicate. – Krunal May 18 '18 at 10:57