gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:05:55 25 4
gpt4 key购买 nike

我需要一个不止一行的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}" 但问题是一样的。

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

我也尝试过使用 Storyboard:

enter image description here

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

enter image description here

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

提前致谢!

最佳答案

试试这个代码:

在 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

}

输出:

enter image description here

关于ios - 如何使用 FontAwesome 制作多行的 UIButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40283992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com