Reputation: 61
Is there a way to set UILabel font to be greater in big device and smaller in small device?
Have I to do it programmatically, checking every time the device size?
My approach is this, now:
class func hightlightPtSize(height: CGFloat) -> CGFloat {
return height / 25
}
class func notSoHighlightPtSize(height: CGFloat) -> CGFloat {
return height / 30
}
class func stdPtSize(height: CGFloat) -> CGFloat {
return height / 35
}
class func sizeForType(height: CGFloat, type: Int) -> CGFloat {
switch type {
case STD:
return stdPtSize(height: height)
case HIGHLIGHT:
return hightlightPtSize(height: height)
case NOT_SO_HIGH:
return notSoHighlightPtSize(height: height)
default:
return 0
}
}
Upvotes: 0
Views: 1916
Reputation: 61
My Swift version of kishan godhani's solution:
let screen = UIScreen.main
var newFontSize = screen.bounds.size.height * (defaultFont / 568.0);
if (screen.bounds.size.height < 500) {
newFontSize = screen.bounds.size.height * (defaultFont / 480.0);
}
label.font = label.font.withSize(newFontSize)
Upvotes: 1
Reputation: 192
I have solution for your problem. Below my code in Objective C.
float newFontSize = [UIScreen mainScreen].bounds.size.height * (fontSize / 568.0);
if ([UIScreen mainScreen].bounds.size.height < 500) {
newFontSize = [UIScreen mainScreen].bounds.size.height * (fontSize / 480.0);
}
self.label.font = [UIFont fontWithName:self.label.font.fontName size:newFontSize];
I hope this helps you.
Upvotes: 4
Reputation: 931
I tried before by making my default font for all labels larger than any possibility used - 60 in my case. Then set the adjustsFontSizeToFitWidth
property to true to let the system size the font for me, while I set the size
of my UILabel
.
To make a label proportionate to the screen size you can use the autoresizing feature of storyboard. With the UILabel
selected, if there is no existing constraints, you can see something like this:
In the right panel of Xcode, click the lines to toggle it on or off, the four line on the sides will tell if the view will maintain it's distance from the sides of it's superview
the two in the square will tell if it resizes with it's superview
in your case, make sure those are on as in the image above. As for the other four that I did not on, you can try experimenting toggling each on or off in combinations with others to find the exact behaviour you want.
If constraints are needed by it's siblings or super/sub views, I can suggest you try a set of constraints like:
It might be slightly verbose, but mainly take note of the first two to get the sizing, set the multiplier of the constraints not constant. The next two are mainly just to satisfy the requirements to properly place your label in the view. You can freely align centers or align top/bottom/leading/trailing in combinations to position it where you want.
Upvotes: 1