Swift UIFont IBInspectable - 有可能吗?

Ott*_*con 8 attributes interface-builder uiview uifont swift

我有一个UIView子类.在此视图中,我创建了实例UIlabel.现在我想在Storyboard中设置这些标签的字体属性.是否有可能作出IBInspectableUIFont

我的一种方法是这样的:

@IBInspectable var fontName: UIFont

但它不会起作用.

把它包起来:我试图得到这个UIView:

字体IBInspectable

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

Vas*_*huk 7

理念

您可以使用Int枚举来选择某种特定字体.

细节

xCode 8.2.1,Swift 3

enum FontType: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
    }
}
Run Code Online (Sandbox Code Playgroud)

课程观点: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)
    }

}
Run Code Online (Sandbox Code Playgroud)

Main.storyboard

在此输入图像描述

结果

在此输入图像描述


在此输入图像描述


在此输入图像描述


在此输入图像描述


Var*_*ria 5

我已经这样

fileprivate var _fontSize:CGFloat = 18
    @IBInspectable
    var font:CGFloat
    {
        set
        {
            _fontSize = newValue
            lblPlaceholder.font = UIFont(name: _fontName, size: _fontSize)
        }
        get
        {
            return _fontSize
        }
    }

    fileprivate var _fontName:String = "Helvetica"
    @IBInspectable
    var fontName:String
    {
        set
        {
            _fontName = newValue
            lblPlaceholder.font = UIFont(name: _fontName, size: _fontSize)
        }
        get
        {
            return _fontName
        }
    }
Run Code Online (Sandbox Code Playgroud)