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

Override font size for 3.5 inch iOS devices

我正在对 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
    }
}

覆盖 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)
            }
        }
    }

}