2016-10-27 4 views
1

오랫동안 나를 괴롭 히고 있습니다. 제목에서 알 수 있듯이, 나는 다양한 색상으로 특정 단어를 강조하는 아이디어가있는 다른 방법을 찾지 못합니다. 예를 들어, "hello", "awesome", "hungry", "sky"... 등의 단어가 포함 된 배열이있는 경우 그런 다음 아래 코드에서 하나의 색상으로 배열 안의 단어를 강조 표시하고 NSBackgroundColorAttributeName으로 설정합니다. 지금까지 실패한 나의 가장 좋은 해결책은 동일한 방법을 여러 개 생성하는 것이 었습니다. 그래서 몇 가지 방법을 만들고 각 방법에 배열을 입력하고 각기 다른 색상을 변경했습니다.NSAtrributedString을 사용하여 UITextVIew에서 여러 색상의 단어를 어떻게 강조 할 수 있습니까?

내 TextView에 입력 된 단어가 파란색으로 변했습니다. 다른 배열의 다른 단어가 내 TextView에 입력 된 후 새로 입력 한 단어는 빨간색이되었지만 이전 단어는 더 이상 강조 표시되지 않았습니다. 다른 배열의 모든 단어를 다르게 강조 표시하고 싶습니다. 나는 그들의 색깔이 사라지 길 바라지 않는다. 나는이 아이디어를 1 주일 동안 생각해 낼 수 없다. 이걸 좀 도와 주실 래요?

func highlightColors(type: [String]){ 

    let attrStr = NSMutableAttributedString(string: myTextView.text) 

    let inputLength = attrStr.string.characters.count 
    let searchString : NSArray = NSArray.init(array: type) 
    for i in 0...searchString.count-1 { 

     let string : String = searchString.object(at: i) as! String 
     let searchLength = string.characters.count 
     var range = NSRange(location: 0, length: attrStr.length) 

     while (range.location != NSNotFound) { 

      range = (attrStr.string as NSString).range(of: string, options: [], range: range) 

      if (range.location != NSNotFound) { 
       coloredStringArray.append(string) 
       attrStr.addAttribute(NSBackgroundColorAttributeName, value: UIColor.blue, range: NSRange(location: range.location, length: searchLength)) 
       attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 20), range: range) 
       range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length)) 
       myTextView.attributedText = attrStr 
       myTextView.font = UIFont(name: "times new roman", size: 20.0) 

      } 
     } 
    } 
} 

답변

1

다음은 특정 색상으로 특정 단어를 강조 표시하기 위해 NSAttributedString을 사용하는 예입니다. 특정 글꼴 및 배경 등으로 강조 표시 할 수있는 방식으로 수정할 수 있습니다.

텍스트보기의 텍스트에서 문자열을 검색 한 다음 속성이 지정된 문자열을 필수 특성으로 수정하는 것이 좋습니다.

당신이 textView.text = blah를 사용하고 있기 때문에 텍스트 뷰는 편집 할 때 속성이 아마 사라지고 그 이유

..

private var textView: UITextView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.textView = UITextView() 
    self.view.addSubview(self.textView) 


    self.textView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true 
    self.textView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true 
    self.textView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true 
    self.textView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true 

    self.textView.translatesAutoresizingMaskIntoConstraints = false 

    self.textView.text = "Test Highlighting Colors on StackOverflow." 

    self.highlight(text: ["Test", "Highlighting", "Colors", "StackOverflow", "Test"], colours: [UIColor.red, UIColor.blue, UIColor.green, UIColor.purple, UIColor.cyan]) 
} 

func highlight(text: [String], colours: [UIColor]) { 
    var ranges = Array<Int>() 
    let attrString = self.textView.attributedText.mutableCopy() as! NSMutableAttributedString 

    for i in 0..<text.count { 

     let str = text[i] 
     let col = colours[i] 
     var range = (self.textView.text as NSString).range(of: str) 

     while (range.location != NSNotFound && ranges.index(of: range.location) != nil) { 
      let subRange = NSMakeRange(range.location + 1, self.textView.text.characters.count - range.location - 1) 
      range = (self.textView.text as NSString).range(of: str, options: NSString.CompareOptions.literal, range: subRange) 
     } 

     if range.location != NSNotFound { 
      ranges.append(range.location) 
      attrString.addAttribute(NSForegroundColorAttributeName, value: col, range: range) 
     } 
    } 

    self.textView.attributedText = attrString 
} 
+0

덕분에, 나는 그것을 구현합니다. 사실, 나는 UserDefaults의 배열을 가지고있다. 아직도 작동합니까? –

+0

안녕하세요, 효과가있었습니다. 그러나 배열의 단어 중 하나가 반복적으로 사용되면 같은 단어의 두 번째 단어는 더 이상 강조 표시되지 않습니다. 어떻게 모든 단어를 강조 표시합니까? –

+0

음, 작동하지 않습니다 ... –