2016-06-26 67 views
-2

我有一個循環遍歷字符串數組以查找字符串。我有一個變量「searchText」,我想在字符串「aText」中用紅色突出顯示。爲搜索項設置字符串屬性Swift 2

for var i = 0; i < aArray?.count; i += 1 { 

     if aArray![i].rangeOfString(searchText) != nil && counter != 100{ 
      counter += 1 
      var aText = aArray![i] 
      var bText = "Example text B" 
      var results = "\(aText) \n \(bText)" 

      resultText.text = (resultText.text + "\n" + results) 

    } 

} 

我已經使用NSMutableAttributedString,但它是沒有用的。我對Swift很陌生,並嘗試了很多方法。主要問題之一是我認爲是因爲它在一個循環中,我正在更新我的UITextView多次。

任何幫助,將不勝感激!

+0

「我已經使用NSMutableAttributedString但它沒用」然後你用錯了,因爲這就是你「用紅色突出顯示」的方式。儘管如此,你的代碼並沒有使用任何屬性的字符串,所以誰能猜出你的嘗試? – matt

+0

如果我使用NSMutableAttributedString,結果文本只顯示一個結果。我不確定它是否可以將字符串歸爲類似resultText.attributedText = mutableStringA + mutableStringB – yousuf12

回答

0
//inside Loop 

if aArray![i] == "searchText" { 
    var searchString:NSString = "The Result is "+aArray![i] 
    let count = aArray![i].length 
    var myMutableString = NSMutableAttributedString(string: searchString.description) 
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range:NSRange(location: 0, length: 14))// i calculated manually . 
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location: 14, length: searchString.length)) 

} 
+0

我在let count = aArray![i] .length 處得到一個錯誤,我將如何實現這一點以確保我的textfield顯示所有結果,而不僅僅是一個? – yousuf12