斯威夫特 - 属性添加到字符串两个字符
问题描述:
之间我有一个这样的字符串:斯威夫特 - 属性添加到字符串两个字符
I am "coding" an "iPhone" app
,我试图将属性添加到每个之间的文本“引号”。
在这种情况下,“编码”和“iPhone”会应用一个属性。
我该如何在Swift中做到这一点?
答
尝试在操场下面:
import PlaygroundSupport
import UIKit
let text = "I am \"coding\" an \"iPhone\" app"
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 320))
PlaygroundPage.current.liveView = textView
let fontSize: CGFloat = 14.0
let plainFont = UIFont.systemFont(ofSize: fontSize)
let boldFont = UIFont.boldSystemFont(ofSize: fontSize)
var attributedText = NSMutableAttributedString(string: text, attributes: [NSFontAttributeName : plainFont])
do {
let regexString = "\"(\\w*)\""
let regex = try NSRegularExpression(pattern: regexString, options: [])
let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count))
for match in matches {
let rangeBetweenQuotes = match.rangeAt(1)
attributedText.setAttributes([NSFontAttributeName : boldFont], range: rangeBetweenQuotes)
}
textView.attributedText = attributedText
} catch let error {
print(error)
}
答
您需要一种方法来查找引号(或您使用的任何分隔符)之间的字符范围。您可以逐字符地逐个字符串,在奇数引号处打开一个新范围,然后关闭范围在偶数编号的引号
或者,您可以使用NSRegularExpression
并使用像matches(in:options:range:)
这样的方法(我不常用正则表达式来解决这个问题。我必须去做一些挖掘工作,并且去除我从来没有非常强烈的RegEx技能。)
一旦你有一组范围,应用你的字符串属性很容易。