Swift: 在 UIbutton 中混合 fontawesome 图标和字符串
Swift: Mix fontawesome icon with string in UIbutton
我在 Swift 5 中使用 FontAwesome.swift
将字体图标添加到我的 UIbutton。我想将 fontawesome 图标与字符串混合,"Database"
。这是我尝试过的:
self.titleLabel?.font = UIFont.fontAwesome(ofSize: 15, style: .solid)
self.setTitle(String.fontAwesomeIcon(name: .database) + " Database", for: UIControl.State.normal)
然而,结果给了我两个相同的图标:
我想要的是这样的:
你可以这样做:
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*
结果如下:
库在源字符串中搜索子字符串并替换相应的图标。其中一个词是 "Database"。可以毫无问题地放置另一个文本。
这样的感觉,就是缺少对这种情况的筛选功能。
我在 Swift 5 中使用 FontAwesome.swift
将字体图标添加到我的 UIbutton。我想将 fontawesome 图标与字符串混合,"Database"
。这是我尝试过的:
self.titleLabel?.font = UIFont.fontAwesome(ofSize: 15, style: .solid)
self.setTitle(String.fontAwesomeIcon(name: .database) + " Database", for: UIControl.State.normal)
然而,结果给了我两个相同的图标:
我想要的是这样的:
你可以这样做:
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*
结果如下:
库在源字符串中搜索子字符串并替换相应的图标。其中一个词是 "Database"。可以毫无问题地放置另一个文本。 这样的感觉,就是缺少对这种情况的筛选功能。