2016-11-04 3 views
0

나는 MacOS 응용 프로그램에서 일하고 있습니다. TextView (NSTextView) 위에 놓인 텍스트의 구문 강조 표시가 선택된 단어 목록과 함께 필요합니다. 단순함을 위해 iPhone Simulator에서 동일한 기능을 실제로 테스트하고 있습니다. 어쨌든 강조 표시 할 단어 목록은 배열 형태입니다. 다음은 내가 가지고있는 것입니다.구문 강조 표시 키워드 사용자 지정 목록 사용하여 텍스트

func HighlightText { 
    let tagArray = ["let","var","case"] 
    let style = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle 
    style.alignment = NSTextAlignment.Left 
    let words = textView.string!.componentsSeparatedByString(" ") // textView.text (UITextView) or textView.string (NSTextView) 
    let attStr = NSMutableAttributedString() 
    for i in 0..<words.count { 
     let word = words[i] 
     if HasElements.containsElements(tagArray,text: word,ignore: true) { 
      let attr = [ 
       NSForegroundColorAttributeName: syntaxcolor, 
       NSParagraphStyleAttributeName: style, 
       ] 
      let str = (i != words.count-1) ? NSAttributedString(string: word.stringByAppendingString(" "), attributes: attr) : NSAttributedString(string: word, attributes: attr) 
      attStr.appendAttributedString(str) 
     } else { 
      let attr = [ 
       NSForegroundColorAttributeName: NSColor.blackColor(), 
       NSParagraphStyleAttributeName: style, 
       ] 
      let str = (i != words.count-1) ? NSAttributedString(string: word.stringByAppendingString(" "), attributes: attr) : NSAttributedString(string: word, attributes: attr) 
      attStr.appendAttributedString(str) 
     } 
    } 
    textView.textStorage?.setAttributedString(attStr) 
} 

class HasElements { 
    static func containsElements(array:Array<String>,text:String,ignore:Bool) -> Bool { 
     var has = false 
     for str in array { 
      if str == text { 
        has = true 
       } 
     } 
     return has 
    } 
} 

간단한 방법은 전체 텍스트 문자열을 공백이있는 단어 ("")로 분리하고 각 단어를 배열 (단어)에 넣는 것입니다. containsElements 함수는 선택한 단어에 배열의 키워드 중 하나 (tagArray)가 포함되어 있는지 여부를 알려줍니다. true를 반환하면 강조 표시된 색상의 NSMutableAttributedString에 단어가 저장됩니다. 그렇지 않으면 일반 색상의 동일한 속성 문자열에 저장됩니다.

이 간단한 방법론의 문제점은 분리 된 단어가 마지막 단어와/n과 다음 단어를 결합한다는 것입니다. 내가

let base = 3 
let power = 10 
var answer = 1 
같은 문자열이있는 경우 예를 들어, 첫 번째는 코드 셋을두고, 다음이 함께 같이하자로 강조 표시됩니다 '하자' '3 \ n 한번.' \ n을 포함하는 단어를 빠른 열거 형으로 분리하면 코드가 새로운 단락을 제대로 감지하지 못합니다. 더 나은 조언을 해주시면 감사하겠습니다. 그냥 MacOS와 iOS 모두에이 주제를 공개 할 예정입니다.

무코스도

답변

1

몇 가지 옵션이 있습니다. String에는 사용자가 정의한 문자 세트로 구분할 수있는 componentsSeparatedByCharactersInSet이라는 함수가 있습니다. 불행히도 이것은 하나 이상의 문자 인 \n으로 분리하기 때문에 작동하지 않습니다.

단어를 두 번 분할 할 수 있습니다. .

let firstSplit = textView.text!.componentsSeparatedByString(" ") 
var words = [String]() 
for word in firstSplit { 
    let secondSplit = word.componentsSeparatedByString("\n") 
    words.appendContentsOf(secondSplit) 
} 

그런데 당신은 줄 바꿈의 의미가없는 것입니다 .. 당신은 다시 그들을 다시 추가해야 할 것입니다 마지막으로

을, 가장 쉬운 해킹은 단순히 :

let newString = textView.text!.stringByReplacingOccurrencesOfString("\n", withString: "\n ") 
let words = newString.componentsSeparatedByString(" ") 

기본적으로 자신 만의 공간을 추가합니다.

+0

감사합니다. 첫 번째 행을 제외한 모든 행이 공백으로 시작한다는 점을 제외하고는 약간 더 잘 작동합니다. 그래서 두 번째 라인은 'let power = 10'이고 세 번째 라인은 'var answer = 1'이 될 것입니다. –

관련 문제