Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61774

How to customize UIBarButtonItem with @IBDesignables?

@IBDesignable class AttributedBarButtonItem: UIBarButtonItem {

    @IBInspectable var fontSize: CGFloat = 22 {
    
        didSet {
        
            let attributes: [String: AnyObject] = [NSFontAttributeName: UIFont(name: "Icomoon", size: fontSize)!]
            setTitleTextAttributes(attributes, forState: .Normal)
        }
    }
}

This is how it looks like in Attributes inspector

enter image description here

But it doesn't change anything:

enter image description here

Upvotes: 0

Views: 585

Answers (3)

rob mayoff
rob mayoff

Reputation: 385560

@IBDesignable doesn't work with UIBarButtonItem, because @IBDesignable only works with UIView subclasses (on iOS), and UIBarButtonItem is not a UIView subclass.

Upvotes: 4

Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61774

It can be customized ONLY via UINavigationBar:

@IBDesignable class AttributedNavigationBar: UINavigationBar {

    @IBInspectable var transparentBackground: Bool = false {

        didSet {

            setBackgroundImage(transparentBackground ? UIImage() : nil, forBarMetrics: .Default)
            shadowImage = transparentBackground ? UIImage() : nil
        }
    }

    @IBInspectable var fontSize: CGFloat = 18
    @IBInspectable var icomoonLeftBarButtonItems: Bool = false {

        didSet {

            let attributes = [NSFontAttributeName: UIFont(name: "Icomoon", size: fontSize)!]

            if let leftBarButtonItems = topItem?.leftBarButtonItems {

                for leftBarButtonItem in leftBarButtonItems {
                    leftBarButtonItem.setTitleTextAttributes(icomoonLeftBarButtonItems ? attributes : nil, forState: .Normal)
                }
            }
        }
    }
}

Works like a charm.

Upvotes: 1

lubilis
lubilis

Reputation: 4160

Try this:

@IBInspectable var fontSize: CGFloat {
    set {
        let attributes: [String: AnyObject] = [NSFontAttributeName: UIFont(name: "Icomoon", size: newValue)!]
        setTitleTextAttributes(attributes, forState: .Normal)
    }
    get {
        return self.fontSize
    }
}

Upvotes: 0

Related Questions