2015-09-11 22 views
1

我想着色textview字符串的所有出現(不僅僅是第一個),但是當我到達循環時,我得到一個無法調用rangeOfString參數。嘗試着色所有出現的textview字符串

我檢查了Swift 2上的rangeOfString:options:range文檔,它看起來很相似。我不確定我做錯了什麼。

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet weak var textView: UITextView! 

    func textView(textView: UITextView){ 

     if textView == self.textView { 

      let nsString = textView.text as NSString 
      let stringLength = textView.text.characters.count 

      var range = NSRange(location: 0, length: textView.text.characters.count) 

      let searchString = textView.text 

      let text = NSMutableAttributedString(string: textView.text) 
      text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, stringLength)) 

      textView.attributedText = text 

      while(range.location != NSNotFound) { 

       range = (textView.text as NSString).rangeOfString(searchString, options: NSStringCompareOptions, range: range) 

       text.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: nsString.rangeOfString("hello")) 
      } 
     } 
    } 
} 
+1

'while(range.location!= NSNotFound)''那麼你沒有改變'range'的值。無限循環肯定。 – anhtu

+0

您需要修改循環以便在整個字符串中移動,並且在完成所有修改後,您應該將文本更新到視圖中。您似乎也對您擁有的不同字符串感到困惑。 – Wain

回答

0

它看起來像你試圖突出搜索欄的用戶輸入。我在這裏如何做:

func highlightedText(text: NSString, inText: NSString, var withColor: UIColor?) -> NSMutableAttributedString { 
    var attributedString = NSMutableAttributedString(string:inText as String) 
    let range = (inText.lowercaseString as NSString).rangeOfString(text.lowercaseString as String) 
    if withColor == nil { 
     if let color = globalTint() { 
      withColor = color 
     } else { 
      withColor = UIColor.redColor() 
     } 
    } 
    attributedString.addAttribute(NSForegroundColorAttributeName, value: withColor! , range: range) 
    return attributedString 
} 
... 
textView.attributedText = highlightedText("string", inText: titleText, color: nil) 
相關問題