【问题标题】:Swift: Mix fontawesome icon with string in UIbuttonSwift:在 UIbutton 中将 fontawesome 图标与字符串混合
【发布时间】:2019-08-20 08:10:27
【问题描述】:

我在 Swift 5 中使用 FontAwesome.swift 为我的 UI 按钮添加了一个 fontawesome 图标。我想将 fontawesome 图标与字符串 "Database" 混合。这是我尝试过的:

self.titleLabel?.font = UIFont.fontAwesome(ofSize: 15, style: .solid)
self.setTitle(String.fontAwesomeIcon(name: .database) + " Database", for: UIControl.State.normal)

但是,结果给了我两个相同的图标:

我想要的是这样的:

【问题讨论】:

  • 在这个 pod 的 Github repo 中没有关于你正在尝试什么的例子,但是你可以使用 Attributed String 和 NSTextAttachment 来做到这一点,请检查这个答案 stackoverflow.com/questions/50040115/…

标签: ios swift uibutton font-awesome


【解决方案1】:

你可以这样做:

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*

结果如下:

【讨论】:

  • 谢谢!我无法理解 NSMutableAttributedString。我猜它来自objective-c?
  • @BanghuaZhao 正确,它只是一个可变属性字符串。
【解决方案2】:

库搜索源字符串中的子字符串并替换相应的图标。其中一个词是“数据库”。可以毫无问题地放置另一个文本。 这样的感觉,就是缺少针对这种情况的筛选功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    相关资源
    最近更新 更多