2017-03-04 95 views

回答

0

嘗試在操場下面:

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) 
} 
0

您需要一種方法來查找引號(或您使用的任何分隔符)之間的字符範圍。您可以逐字符地逐個字符串,在奇數引號處打開一個新範圍,然後關閉範圍在偶數編號的引號

或者,您可以使用NSRegularExpression並使用像matches(in:options:range:)這樣的方法(我不常用正則表達式來解決這個問題。我必須去做一些挖掘工作,並且去除我從來沒有非常強烈的RegEx技能。)

一旦你有一組範圍,應用你的字符串屬性很容易。