覆盖3.5英寸iOS设备的字体大小

时间:2015-10-22 18:36:08

标签: ios swift fonts uitextfield

我要对UILabelUITextField进行子类化,以便仅在3.5英寸设备上更改字体大小(因为这不能使用4和4.7独立的大小类来完成英寸设备)。

如果字体在layoutSubviews()中完成,则字体会发生变化,但会重复调用,因此字体大小最终为零。我试图找到另一个地方设置它只调用一次,仍然可以覆盖字体大小。

代码:

if (UIDevice.currentDevice().orientation == .Portrait) {
    if (UIScreen.mainScreen().bounds.size.height < 568) {
        self.font = UIFont(name: "Score Board", size: (self.font.pointSize - CGFloat(10.0)))
    } else {
        self.font = UIFont(name: "Score Board", size: self.font.pointSize)
    }
} else {
    if (UIScreen.mainScreen().bounds.size.width < 568) {
        self.font = UIFont(name: "Score Board", size: (self.font.pointSize - CGFloat(10.0)))
    } else {
        self.font = UIFont(name: "Score Board", size: self.font.pointSize)
    }
}

我还在didMoveToSuperview()willMovetoSuperview()中尝试了它,它只被调用一次,但它实际上并没有改变字体。我也在init中尝试过,但字体也没有设置。

import Foundation
import UIKit

class CustomUILabel : UILabel {

    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        // Code from above
    }
}

1 个答案:

答案 0 :(得分:1)

覆盖didSet属性的font

class MyLabel : UILabel {

    private func shouldShrinkFont() -> Bool {
        let size = UIScreen.mainScreen().bounds.size
        // This check works regardless of orientation.
        return size.width + size.height == 480 + 320
    }

    override var font: UIFont! {
        didSet {
            if shouldShrinkFont() {
                super.font = UIFont(name: "Score Board", size: font.pointSize - 10)
            }
        }
    }

}