Swift中的UIFont是否支持IBInspectable?

10
我有一个名为 UIView 的子类,在这个视图中我创建了 UILabel 实例。现在我想在故事板中设置这些标签的字体属性。是否可以为 UIFont 创建一个 IBInspectable?我的一种方法是这样的:@IBInspectable var fontName: UIFont,但它不起作用。总之,我试图在 UIView 中实现这个: Font IBInspectable 希望有人能帮助我,谢谢! :)

2
真遗憾,如果不进行黑客攻击,这是不可能实现的。苹果应该在Xcode 9中加入这个功能。 - Tamás Sengel
3个回答

10

Idea

您可以使用Int枚举来选择特定字体之一。

Details

xCode 8.2.1,Swift 3

Code

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
    }
}
视图: 视图
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

图片描述

结果

图片描述


图片描述


图片描述


图片描述


8
我已经这样做了。
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
        }
    }

0
  @IBInspectable var isShowfontName : Bool  = false
    @IBInspectable var fontFamilyIndex : CGPoint = CGPoint(x: -1, y: -1 )
    var  leoFontName : String? {

        if Int(fontFamilyIndex.x) >= 0 && Int(fontFamilyIndex.x) < UIFont.familyNames.sorted().count {

            let fontNames = UIFont.fontNames(forFamilyName: UIFont.familyNames.sorted()[Int(fontFamilyIndex.x)])

            if Int(fontFamilyIndex.y) >= 0 && Int(fontFamilyIndex.y) < fontNames.count {

                return  fontNames[Int(fontFamilyIndex.y)]
            }


            return fontNames.first ?? nil

        }



        return nil
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接