如何使用 FontAwesome 制作多行的 UIButton?

How can I make an UIButton with more than one line using FontAwesome?

我需要一个不止一行的 UIButton。第一行将有一个 FontAwesome 的图标,第二行是一个解释该图标的词。

此外,每行两行的字体大小必须不同。

这是我目前拥有的:

@IBOutlet weak var btnProfile: UIButton!

let paraStyle = NSMutableParagraphStyle()
paraStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
paraStyle.alignment = NSTextAlignment.center

let icon = NSMutableAttributedString(string: "\u{f082}", attributes: [NSFontAttributeName: UIFont.init(name: "FontAwesome", size: 40)])
let text = NSMutableAttributedString(string:"\nProfile", attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 12.0)])
        
icon.append(text)
icon.addAttribute(NSParagraphStyleAttributeName, value: paraStyle, range: NSRange(location:0,length: icon.length))
        
btnProfile.setAttributedTitle(icon, for: .normal)

但我收到以下错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue renderingMode]: unrecognized selector sent to instance

我也试过用里面有询问符号的方块代替"\u{f082}",但问题是一样的。

我知道问题出在最后两行,因为如果我对它们进行注释,应用程序不会抛出任何异常。

我也用故事板试过:

而且效果几乎不错。这两行都用图标 + 文本显示,但文本具有图标的字体和字体大小,我希望它们不同。这里是截图:

我做错了什么?我不在乎我是通过代码还是通过故事板来解决这个问题。

提前致谢!

试试这个代码:

在 Swift 3.

中测试
override func viewDidLoad() {
    super.viewDidLoad()

     //applying the line break mode
    btnProfile?.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping;

    let buttonText: NSString = "⭐️ Favourite\nProfile"

    //getting the range to separate the button title strings
    let newlineRange: NSRange = buttonText.range(of: "\n")

    //getting both substrings
    var substring1: NSString = ""
    var substring2: NSString = ""

    if(newlineRange.location != NSNotFound) {
        substring1 = buttonText.substring(to: newlineRange.location) as NSString
        substring2 = buttonText.substring(from: newlineRange.location) as NSString
    }


    //assigning diffrent fonts to both substrings
    let font:UIFont? = UIFont(name: "Chalkduster", size: 50.0)
    let attrString = NSMutableAttributedString(string: substring1 as String, attributes: NSDictionary(object: font!, forKey: NSFontAttributeName as NSCopying) as? [String : Any])        
    let font1:UIFont? = UIFont(name: "Noteworthy-Light", size: 30.0)
    let attrString1 = NSMutableAttributedString(string: substring2 as String, attributes: NSDictionary(object: font1!, forKey: NSFontAttributeName as NSCopying) as? [String : Any]) 

    //appending both attributed strings
    attrString.append(attrString1)

    //assigning the resultant attributed strings to the button
    btnProfile.setAttributedTitle(attrString, for: UIControlState.normal)
    btnProfile.titleLabel?.textAlignment = .center

}

输出: