Reputation: 343
I have a string like this:
I am "coding" an "iPhone" app
and I am trying to add attributes to the text between each "quotation mark."
In this case "coding" and "iPhone" would have an attribute applied.
How can I do this in Swift?
Upvotes: 0
Views: 1100
Reputation: 326
Try the following in a Playground:
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)
}
Upvotes: 1
Reputation: 131408
You need a way to find the ranges of characters between the quotation marks (or whatever delimiter you're using. You could walk the string character by character, opening a new range at an odd number of quotes, and closing the range at even numbered quotes.
Alternatively you could use an NSRegularExpression
and use a method like matches(in:options:range:)
. (I don't use regular expressions often enough to be able to give you one for this problem off the top of my head. I'd have to go do some digging and dust off my never-very-strong RegEx skills.)
Once you have a set of ranges, applying your string attributes is easy.
Upvotes: 0