【发布时间】:2016-07-01 06:56:15
【问题描述】:
我在 storyBoard 中添加了 autoLayout(w:Any,h:Any)
但由于字体大小固定,所有设备的字体大小都相同 (4、4.7、5.5英寸)
4 英寸的看起来不错。但是5.5寸,太小了
我想在任何设备上动态增加和减小 UIlabel 字体大小。
有什么想法吗?
【问题讨论】:
标签: xcode swift responsive-design storyboard size
我在 storyBoard 中添加了 autoLayout(w:Any,h:Any)
但由于字体大小固定,所有设备的字体大小都相同 (4、4.7、5.5英寸)
4 英寸的看起来不错。但是5.5寸,太小了
我想在任何设备上动态增加和减小 UIlabel 字体大小。
有什么想法吗?
【问题讨论】:
标签: xcode swift responsive-design storyboard size
我找到了解决方案
我做了一门课
class UILabelDeviceClass : UILabel {
@IBInspectable var iPhoneFontSize:CGFloat = 0 {
didSet {
overrideFontSize(iPhoneFontSize)
}
}
func overrideFontSize(fontSize:CGFloat){
let currentFontName = self.font.fontName
var calculatedFont: UIFont?
let bounds = UIScreen.mainScreen().bounds
let height = bounds.size.height
switch height {
case 480.0: //Iphone 3,4,SE => 3.5 inch
calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.7)
self.font = calculatedFont
break
case 568.0: //iphone 5, 5s => 4 inch
calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.8)
self.font = calculatedFont
break
case 667.0: //iphone 6, 6s => 4.7 inch
calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.9)
self.font = calculatedFont
break
case 736.0: //iphone 6s+ 6+ => 5.5 inch
calculatedFont = UIFont(name: currentFontName, size: fontSize)
self.font = calculatedFont
break
default:
print("not an iPhone")
break
}
}
}
然后,设置类
然后,设置值
编码愉快!
【讨论】:
height = max(bounds.size.height, bounds.size.width)
检查屏幕大小并据此操作字体大小:
let screenSize = UIScreen.mainScreen().bounds.size
if screenSize.height < 568 {
//Set font size for 4
} else if screenSize.height < 568 {
//Set font size for 5
} else if screenSize.height < 568 {
//Set font size for 6
} else {
//Set font size for 6+
}
更新:
扩展 UILabel 类来设置你的标签:
extension UILabel {
func setupLabelDynamicSize(size size:CGFloat) {
let screenSize = UIScreen.mainScreen().bounds.size
if screenSize.height < 568 {
//Set self.font equal size
} else if screenSize.height < 568 {
//Set self.font equal size + 1
} else if screenSize.height < 568 {
//Set self.font equal size + 2
} else {
//Set self.font equal size + 3
}
}
}
然后,无论您有想要动态大小的标签,只需调用:
labelObject.setupLabelForDynamicSize(size: 14)
【讨论】:
不,您不能只为 iPhone 5.5 配置尺寸等级。尺寸等级无法区分 iPhone 5、6 和 6Plus。
只有 1 个边缘保护壳仅支持 iPhone 5.5 横向:
regular width, compact height: 5.5" iPhone in Landscape
您可以做到这一点的唯一方法是在您的代码中检查设备大小!
【讨论】:
How can do it in storyboard ?无论如何,我会更新我的答案
customTag 并为此属性创建 IBDesignable。在界面生成器中,为 UILabel (s) 设置相同的customTag 具有相同的字体大小。在您的代码中,检查customTag 并设置适当的字体大小。但这不是很好!