This is device wise font change code if open iPad then font size is big and if open small device like iPhone SE, 8, 6 elc, then font size is small according small device
This code is perfectly run but in this code add font type added.
How can I add it?
extension UIFont {
// static func setFont(type: fontType = .clashGroteskSemibold, size: CGFloat = UIFont.systemFontSize) -> UIFont {
// return UIFont(name: type.rawValue, size: size.dp) ?? UIFont()
// }
class func appFont(
ofSize size : CGFloat = UIFont.systemFontSize,
weight : Weight = .semibold
) -> UIFont {
return UIFont.systemFont(ofSize: size.dp, weight: weight)
}
}
extension CGFloat {
var dp: CGFloat {
let width = UIScreen.main.bounds.width
let device = UIScreen.main.traitCollection.userInterfaceIdiom
if (device == .phone) {
if (width <= 375) {
// iPhone(SEGen2 6, 6s, 7, 8, X, Xs, 11pro, 12mini, 13mini)
return self * 0.60
} else if (width <= 414) {
// iPhone(6+, 6s+, 7+, 8+, XsMax, XR, 11, 11proMax, 12, 12pro, 13, 13pro)
return self
}
}
else if (device == .pad) {
if (width <= 1024) {
// ipad(miniGen6, )
return self * 2.0
}
}
return self
}
}
call func code
cell.stepsLabel.font = UIFont.appFont(ofSize: 32, weight: .semibold)
I have add custome font and font type but not warking I have face error is optional valur unrapped this type of error are faced.
extension UIFont {
public enum fontType: String {
case clashGroteskSemibold = "ClashGrotesk-Semibold"
case clashGroteskRegular = "ClashGrotesk-Regular"
case clashGroteskMedium = "ClashGrotesk-Medium"
case clashGroteskLight = "ClashGrotesk-Light"
case clashGroteskExtralight = "ClashGrotesk-Extralight"
case clashGroteskBold = "ClashGrotesk-Bold"
}
class func appFont(
type: fontType = .clashGroteskSemibold,
ofSize size : CGFloat = UIFont.systemFontSize
) -> UIFont {
return UIFont(name: type.rawValue, size: size.dp)!
}
}
To use custom font, make sure register font in info.plist under "Fonts provided by application" property. Note: Font name should be same as filename with file extension.
Register Custom Font:
And also ensure that the custom font is available in your app's target. You can confirm from File Inspector for custom font file in Target Membership. For Reference, look into attached image.
Font Target:
To avoid nil value errors, use this code in UIFont extension:
enum FontType: String {
case clashGroteskBold = "ClashGrotesk-Bold"
case clashGroteskSemibold = "ClashGrotesk-Semibold"
case clashGroteskRegular = "ClashGrotesk-Regular"
case clashGroteskMedium = "ClashGrotesk-Medium"
case clashGroteskLight = "ClashGrotesk-Light"
case clashGroteskExtralight = "ClashGrotesk-Extralight"
}
class func appFont(type: FontType = .clashGroteskSemibold, ofSize size : CGFloat = UIFont.systemFontSize) -> UIFont {
guard let font = UIFont(name: type.rawValue, size: size.dp) else {
return self.systemFont(ofSize: size.dp)
}
return font
}