SWIFT UIFON IBInspectable-有可能吗?

人气:480 发布:2022-10-16 标签: attributes uiview swift interface-builder uifont

问题描述

我有一个UIView子类。在此视图中,我创建了UIlabel的实例。 现在我想在故事板中设置这些标签的字体属性。是否可以为UIFont创建IBInspectable

我的方法之一是:

@IBInspectable var fontName: UIFont

但它不起作用。

总结:我正在尝试为UIView获取此信息:

希望有人能帮助我,谢谢!:)

推荐答案

想法

您可以使用Int枚举选择其中一种特定字体。

详细信息

Xcode 8.2.1,SWIFT 3

代码

枚举字体类型:int

import UIKit
enum FontType: Int {
    case Default = 0, Small, Large

    var fount: UIFont {
        switch self {
            case .Default:
                return UIFont.systemFont(ofSize: 17)
            case .Small:
                return UIFont.systemFont(ofSize: 12)
            case .Large:
                return UIFont.systemFont(ofSize: 24)
        }
    }


    static func getFont(rawValue: Int) -> UIFont  {
        if let fontType = FontType(rawValue: rawValue) {
            return fontType.fount
        }
        return FontType.Default.fount
    }
}

类视图:UIView

import UIKit
@IBDesignable
class View: UIView {

    private var label: UILabel!

    @IBInspectable var textFont:Int = 0

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        label = UILabel(frame: CGRect(x: 20, y: 20, width: 120, height: 40))
        label.text = "Text"
        label.textColor = .black
        label.font = FontType.getFont(rawValue: textFont)
        addSubview(label)
    }

}

Main.Storyboard

结果

352