2017-01-13 7 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、オプション:.caseInsensitive) " – mholgate

関連する問題