Swift Uifont Ibinspectable - Is It Possible

Swift UIFont IBInspectable - is it possible?

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

Sample Image

Results

Sample Image


Sample Image


Sample Image


Sample Image

Is it possible to make @IBDesignable override Interface Builder values?

I have created new IBInspectable as testFonts :

import UIKit

@IBDesignable

class CustomButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
self.customInit()
}

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.customInit()
}

func customInit () {
titleLabel?.font = UIFont.systemFontOfSize(20)
}

convenience init() {
self.init(frame:CGRectZero)
self.customInit()
}

override func awakeFromNib() {
super.awakeFromNib()
self.customInit()
}

override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.customInit()
}
}

Hope it helps you :)

This is working for me.

Change font of labels with @IBDesignable

The first method which is called after the view is fully initialized from nib is UIView's awakeFromNib() method. You can override and use it to modify view's or subviews properties

Is it possible to remove a superclass' IBInspectable property?

Sounds like if you want to extend UIView class and remove background attribute from Interface Builder. That's not possible from structure.

Then, if you try to override font attribute in your inherited UIButton class for customization (as code below), you'll receive compiler errors because you cannot override a stored property of super class.

override var font: UIFont {
set {

}
get {

}
}


Related Topics



Leave a reply



Submit