Vaberer / Font-Awesome-Swift

Font Awesome swift library for iOS.
MIT License
743 stars 125 forks source link

Any chance of being able to use this on a tab bar item #11

Closed n8stowell82 closed 8 years ago

n8stowell82 commented 8 years ago

I am not even sure this is possible, but is there any chance that this could be expanded to be used on a tab bar item? Thanks!

Vaberer commented 8 years ago

Hello, for now it is on possible because font awesome icon is actually a text and tabbar item's parameter is an image. There has to be option how to convert it to the image but for now, it's not possible. I am open to any suggestions and pull requests :)

snaill commented 8 years ago

this is code, I hope useful.

public extension UIImage {

    public convenience init(icon: FAType, size: CGSize, textColor: UIColor = UIColor.blackColor(), backgroundColor: UIColor = UIColor.clearColor()) {

        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = NSTextAlignment.Center

        // Taken from FontAwesome.io's Fixed Width Icon CSS
        let fontAspectRatio: CGFloat = 1.28571429
        let fontSize = min(size.width / fontAspectRatio, size.height)

        FontLoader.loadFontIfNeeded()
        let font = UIFont(name: FAStruct.FontName, size: fontSize)
        assert(font != nil, FAStruct.ErrorAnnounce)
        let attributes = [NSFontAttributeName: font!, NSForegroundColorAttributeName: textColor, NSBackgroundColorAttributeName: backgroundColor, NSParagraphStyleAttributeName: paragraph]

        let attributedString = NSAttributedString(string: icon.text!, attributes: attributes)
        UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
        attributedString.drawInRect(CGRectMake(0, (size.height - fontSize) / 2, size.width, fontSize))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.init(CGImage: image.CGImage!, scale: image.scale, orientation: image.imageOrientation)
    }

}

public extension UITabBarItem {

    public func setFAIcon(icon: FAType) {

        image = UIImage(icon: icon, size: CGSize(width: 30, height: 30))
    }
}
snaill commented 8 years ago

for UISegmentedControl:

public extension UISegmentedControl {

    public func setFAIcon(icon: FAType, forSegmentAtIndex segment: Int) {

        FontLoader.loadFontIfNeeded()
        let font = UIFont(name: FAStruct.FontName, size: 23)
        assert(font != nil, FAStruct.ErrorAnnounce)
        setTitleTextAttributes([NSFontAttributeName: font!], forState: .Normal)
        setTitle(icon.text, forSegmentAtIndex: segment)
    }
}
Vaberer commented 8 years ago

Hello,

Thanks for your contribution. Everything works and you can change tabbarItem i.e.

tabBarController?.tabBar.items?.first?.setFAIcon(FAType.FATwitter)