Reputation: 1556
I am using FontAwesome.swift
in Swift 5 to add a fontawesome icon to my UIbutton. I want to mix fontawesome icon with a String, "Database"
. Here is what I have tried:
self.titleLabel?.font = UIFont.fontAwesome(ofSize: 15, style: .solid)
self.setTitle(String.fontAwesomeIcon(name: .database) + " Database", for: UIControl.State.normal)
However, the result gives me two identical icons:
What I want is something like this:
Upvotes: 0
Views: 916
Reputation: 64
The library search substrings in the source string and replace the corresponding icon. One of these words is "Database". Another text can be put without problems. Such a feeling, that there is a lack of screening functionality for such situations.
Upvotes: 1
Reputation: 18591
You could do it this way:
let str = String.fontAwesomeIcon(name: .database) + " Database"
let attributedStr = NSMutableAttributedString(string: str)
//Apply FontAwesome to the first character
let range1 = NSRange(location: 0, length: 1)
attributedStr.addAttribute(.font,
value: UIFont.fontAwesome(ofSize: 15, style: .solid),
range: range1)
//Apply the system font to the rest of the string
let range2 = NSRange(location: 1, length: (str as NSString).length - 1)
attributedStr.addAttribute(.font,
value: UIFont.systemFont(ofSize: 15),
range: range2)
//Set the attributed text for the button
self.setAttributedTitle(attributedStr, for: .normal) //self being the button *itself*
And here is the result:
Upvotes: 2