我需要一个包含多行的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)
但是我收到以下错误:
由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [_ SwiftValue renderingMode]:无法识别的选择器发送到实例
我也试过使用带有询问符号的方块代替"\u{f082}"
,但问题是一样的。
我知道问题出现在最后两行,因为如果我评论它们,应用程序不会抛出任何异常。
我也尝试使用故事板:
它的效果非常好。这两行都显示为图标+文本,但文本具有图标的字体和字体大小,我希望它们不同。这是一个截图:
我做错了什么?如果我通过代码或故事板解决这个问题,我不在乎。
提前致谢!
答案 0 :(得分:1)
试用此代码:
在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
}
输出: