2017-01-13 117 views
1

我有一個項目表,每個項目都有一個標籤。我還有一個搜索欄,用於根據mySearchBar.text是否爲myLabel.text的子字符串來篩選表中的項目。使粗體字符串的一部分與搜索字符串匹配

這一切都工作正常,但我想大膽的標籤文本的部分匹配搜索字符串。

最終產品與Google地圖搜索類似。

enter image description here

回答

2

這裏是我結束了實施示例:

@IBOutlet weak var mySearchBar: UISearchBar! 
@IBOutlet weak var myLabel: UILabel! 

... 

func makeMatchingPartBold(searchText: String) { 

    // check label text & search text 
    guard 
     let labelText = myLabel.text, 
     let searchText = mySearchBar.text 
    else { 
     return 
    } 

    // bold attribute 
    let boldAttr = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: myLabel.font.pointSize)] 

    // check if label text contains search text 
    if let matchRange: Range = labelText.lowercased().range(of: searchText.lowercased()) { 

     // get range start/length because NSMutableAttributedString.setAttributes() needs NSRange not Range<String.Index> 
     let matchRangeStart: Int = labelText.distance(from: labelText.startIndex, to: matchRange.lowerBound) 
     let matchRangeEnd: Int = labelText.distance(from: labelText.startIndex, to: matchRange.upperBound) 
     let matchRangeLength: Int = matchRangeEnd - matchRangeStart 

     // create mutable attributed string & bold matching part 
     let newLabelText = NSMutableAttributedString(string: labelText) 
     newLabelText.setAttributes(boldAttr, range: NSMakeRange(matchRangeStart, matchRangeLength)) 

     // set label attributed text 
     myLabel.attributedText = newNameText 
    } 
} 
+1

而不是使用 '.lowercased()範圍(作者:searchText.lowercased())。' 你可以用」。範圍(of:searchText,options:.caseInsensitive)「 – mholgate