首页 > 解决方案 > Swift 在 addAttribute 中设置当前字体

问题描述

我有一个加号按钮来增加字体大小和一个减号按钮来减小字体大小。现在我尝试使用搜索栏在我的文本视图中突出显示单词。到目前为止它工作得很好,但不幸的是没有保留当前的字体大小,而是将其恢复为默认字体大小。我的解决方案是调用 addAttributes 并指定 .font,不幸的是我不知道在值和范围中输入什么。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

do
    {
        if let searchString = searchBar.text, let baseString = textNotiz.text {

            let attributed = NSMutableAttributedString(string: baseString)
            attributed.addAttribute(.font, value: "??", range: "??" )
            if searchString.count > 0 && baseString.count > 0 {

                let regex = try! NSRegularExpression(pattern: searchString,options: .caseInsensitive)
                for match in regex.matches(in: baseString, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: baseString.count)) as [NSTextCheckingResult] {
                    attributed.addAttribute(.backgroundColor, value: UIColor.yellow, range: match.range)
                }
                self.textNotiz.attributedText = attributed

            } else {

                textNotiz.attributedText = attributed

            }
        }

    }
}

标签: swiftnsattributedstring

解决方案


推荐阅读