Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UIFont IBInspectable - is it possible?

I have a UIView subclass. In this view I create instances of UIlabel. Now I want to set the font attributes for these labels in the Storyboard. Is it possible to make an IBInspectable for UIFont?

One of my approaches was this:

@IBInspectable var fontName: UIFont

But it won't work.

To wrap it up: I trying to get this for the UIView:

Font IBInspectable

I hope someone can help me, thank you! :)

like image 484
Ottacon Avatar asked Mar 29 '17 09:03

Ottacon


2 Answers

I have done this way

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
        }
    }
like image 90
Varun Naharia Avatar answered Oct 05 '22 08:10

Varun Naharia


Idea

You can use Int enums to select one of the certain fonts.

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
    }
}

class View: 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

enter image description here

Results

enter image description here


enter image description here


enter image description here


enter image description here

like image 32
Vasily Bodnarchuk Avatar answered Oct 05 '22 09:10

Vasily Bodnarchuk