[英]Adjust UILabel font size without .adjustsFontForContentSizeCategory
[英]Adjust UILabel font size for device dimension
有没有一种方法可以将UILabel字体设置为在大设备中较大而在小设备中较小?
我是否需要以编程方式进行操作,每次检查设备大小时都进行检查?
现在,我的方法是这样的:
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
}
}
我有解决您问题的方法。 在我的目标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];
我希望这可以帮助你。
之前,我尝试过使所有标签的默认字体都大于使用的任何字体-在我的情况下为60。 然后,将adjustsFontSizeToFitWidth
属性设置为true,以让系统为我设置字体大小,同时设置UILabel
的size
。
要使标签与屏幕尺寸成比例,可以使用情节提要的自动调整大小功能。 选择UILabel
,如果不存在现有约束,则可以看到类似以下内容的内容:
在Xcode的右面板中,单击线条以将其打开或关闭,侧面的四条线将告诉您视图是否保持其与superview
的距离,而广场中的两条线将告诉您是否调整其尺寸。 superview
您的情况而定,请确保如上图所示启用这些功能。 至于我没有提到的其他四个,您可以尝试与其他人一起切换开或关,以找到所需的确切行为。
如果兄弟姐妹或超级/子视图需要约束,我建议您尝试一组约束,例如:
这可能是稍微详细,但主要是注意到前两次拿到大小,设置的约束不恒定的乘数 。 接下来的两个主要是为了满足将标签正确放置在视图中的要求。 您可以自由对齐中心,也可以组合对齐顶部/底部/前导/尾随以将其放置在所需的位置。
我的Kishan Godhani解决方案的Swift版本:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.