将与搜索字符串匹配的字符串的一部分加粗
Make part of a string bold that matches a search string
我有 table 个项目,每个项目都有一个标签。我还有一个搜索栏,用于根据 mySearchBar.text
是否是 myLabel.text
的子字符串来过滤 table 中的项目。
一切正常,但我想将与搜索字符串匹配的标签文本部分加粗。
最终产品将类似于 Google 地图搜索。
这是我最终实现的示例:
@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
}
}
Swift 4 : XCode 9.x
private func filterAndModifyTextAttributes(searchStringCharacters: String, completeStringWithAttributedText: String) -> NSMutableAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: completeStringWithAttributedText)
let pattern = searchStringCharacters.lowercased()
let range: NSRange = NSMakeRange(0, completeStringWithAttributedText.characters.count)
var regex = NSRegularExpression()
do {
regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options())
regex.enumerateMatches(in: completeStringWithAttributedText.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) {
(textCheckingResult, matchingFlags, stop) in
let subRange = textCheckingResult?.range
let attributes : [NSAttributedStringKey : Any] = [.font : UIFont.boldSystemFont(ofSize: 17),.foregroundColor: UIColor.red ]
attributedString.addAttributes(attributes, range: subRange!)
}
}catch{
print(error.localizedDescription)
}
return attributedString
}
How to use :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle , reuseIdentifier: "Cell")
cell.textLabel?.attributedText = self.filterAndModifyTextAttributes(searchStringCharacters: self.textFromSearchBar, completeStringWithAttributedText: searchResultString)
return cell
}
我有 table 个项目,每个项目都有一个标签。我还有一个搜索栏,用于根据 mySearchBar.text
是否是 myLabel.text
的子字符串来过滤 table 中的项目。
一切正常,但我想将与搜索字符串匹配的标签文本部分加粗。
最终产品将类似于 Google 地图搜索。
这是我最终实现的示例:
@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
}
}
Swift 4 : XCode 9.x
private func filterAndModifyTextAttributes(searchStringCharacters: String, completeStringWithAttributedText: String) -> NSMutableAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: completeStringWithAttributedText)
let pattern = searchStringCharacters.lowercased()
let range: NSRange = NSMakeRange(0, completeStringWithAttributedText.characters.count)
var regex = NSRegularExpression()
do {
regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options())
regex.enumerateMatches(in: completeStringWithAttributedText.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) {
(textCheckingResult, matchingFlags, stop) in
let subRange = textCheckingResult?.range
let attributes : [NSAttributedStringKey : Any] = [.font : UIFont.boldSystemFont(ofSize: 17),.foregroundColor: UIColor.red ]
attributedString.addAttributes(attributes, range: subRange!)
}
}catch{
print(error.localizedDescription)
}
return attributedString
}
How to use :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle , reuseIdentifier: "Cell")
cell.textLabel?.attributedText = self.filterAndModifyTextAttributes(searchStringCharacters: self.textFromSearchBar, completeStringWithAttributedText: searchResultString)
return cell
}