Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/105.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 突出显示UITableView单元格中的搜索结果_Ios_Uitableview_Highlight_Searchbar - Fatal编程技术网

Ios 突出显示UITableView单元格中的搜索结果

Ios 突出显示UITableView单元格中的搜索结果,ios,uitableview,highlight,searchbar,Ios,Uitableview,Highlight,Searchbar,我在表视图中实现了一个搜索栏。现在我想强调一下结果。例如,如果我键入了两个字母,那么这两个字母应该在从搜索栏下拉的结果表格视图中突出显示。有人能帮我做这件事吗?我知道我应该使用自定义单元格,但我无法实现它。您可以通过从结果字符串中查找搜索词字符串范围并在该范围内添加属性字符串来实现这一点。找到下面的示例代码 目标-C NSString *searchTerm = /* SEARCH_TERM */; NSString *resultText = /* YOUR_RESULT_TEXT */;

我在
表视图中实现了一个搜索栏。现在我想强调一下结果。例如,如果我键入了两个字母,那么这两个字母应该在从搜索栏下拉的结果
表格视图中突出显示。有人能帮我做这件事吗?我知道我应该使用自定义单元格,但我无法实现它。

您可以通过从结果字符串中查找搜索词字符串范围并在该范围内添加属性字符串来实现这一点。找到下面的示例代码

目标-C

NSString *searchTerm = /* SEARCH_TERM */;
NSString *resultText = /* YOUR_RESULT_TEXT */;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:resultText];

NSString *pattern = [NSString stringWithFormat:@"(%@)", searchTerm];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:nil];
NSRange range = NSMakeRange(0, resultText.length);

[regex enumerateMatchesInString:resultText options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSRange subStringRange = [result rangeAtIndex:1];

    [attributedString addAttribute:NSForegroundColorAttributeName
                             value:[UIColor redColor]
                             range:subStringRange];
}];
Swift(已测试)


@Vijay对这篇文章有一个好的、正确的答案

我为了自己的目的(在搜索结果中加粗文本)稍微修改了一下,创建了一个函数,该函数接受
searchString
和您要修改的字符串-
resultString
-并返回可应用于
UILabel
AttributeString

我还检查了
lowercasesetring
属性,因此无论我在搜索栏中键入什么,我的字符串都将匹配字符而不是大小写(此要求可能会有所不同,取决于您的用例)

注意:我有一个自定义的粗体字体,但您可以始终使用
UIFont.boldSystemFontOfSize(fontSize:CGFloat)
或类似的方法来获得类似效果

然后,只需通过执行以下操作将结果添加到标签中:

下面是在tableview中为文本添加属性的第二种方法

   let initialtext =   "Hello World"
    let attrString: NSMutableAttributedString = NSMutableAttributedString(string: initialtext)

let range: NSRange = (initialtext as NSString).rangeOfString(("World" , options:NSStringCompareOptions.CaseInsensitiveSearch])


    attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)


    cell!.textLabel?.attributedText = attrString

尽量保持苗条。 该函数返回一个属性字符串,其中searchText以粗体显示。 Swift 4.2+

  private func boldedString(with baseString: String, searchString: String, fontSize: CGFloat) -> NSAttributedString? {
    guard let regex = try? NSRegularExpression(pattern: searchString, options: .caseInsensitive) else {
        return nil
    }

    let attributedString = NSMutableAttributedString(string: baseString)
    let boldFont = UIFont.systemFont(ofSize: fontSize, weight: .bold)
    regex
      .matches(in: baseString, options: .withTransparentBounds,
               range: NSRange(location: 0, length: baseString.utf16.count))
      .forEach {
        attributedString.addAttributes([.font: boldFont], range: $0.range)
    }
    return attributedString
  }
在单元格中,您需要添加如下代码进行配置:

func configure(with text: String, searchText: String?) {
  if let boldedAddress = boldedString(with: text,
                                      searchString: searchText,
                                      fontSize: titleLabel.font.pointSize) {
    titleLabel.attributedText = boldedAddress
  } else {
    titleLabel.text = locationInfo.location.address
  }
}

Vijayvir回答的Swift 5版本:

让initialtext=“你好,世界!”
让attrString:NSMutableAttributeString=NSMutableAttributeString(字符串:initialtext)
let range=(initialtext作为NSString)。range(of:“World”,选项:。不区分大小写)
attrString.addAttribute(nsAttributeString.Key.foregroundColor,值:UIColor.red,范围:range)
cell.textLabel?.attributedText=attrString
2020年更新: 这里有一个简单的
String
扩展,您可以使用它轻松创建属性字符串

扩展字符串{
func highlightText(
_文本:字符串,
颜色:UIColor,
案例不敏感:Bool=false,
font:UIFont=.preferredFont(forTextStyle:.body))->NSAttributedString
{
让attrString=nsmutableAttributeString(字符串:self)
let range=(本身作为NSString)。range(of:text,options:caseInsensitivie?.caseinsensitives:[])
attrString.addAttribute(
.前底色,
值:颜色,
射程:射程)
attrString.addAttribute(
.font,
值:字体,
范围:NSRange(位置:0,长度:attrString.length))
返回属性字符串
}
}

此解决方案可用于转义字符,如({}[]()'”)此解决方案是用SWIFT 5编写的

func generateAttributedString(with searchTerm: String, targetString: NSAttributedString) -> NSAttributedString? {
    let attributedString = NSMutableAttributedString(attributedString: targetString)
    do {

        let regex = try NSRegularExpression(pattern:  NSRegularExpression.escapedPattern(for: searchTerm).trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .regularExpression, locale: .current), options: .caseInsensitive)
        let range = NSRange(location: 0, length: targetString.string.utf16.count)
        attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: range)


        for match in regex.matches(in: targetString.string.folding(options: .regularExpression, locale: .current), options: .withTransparentBounds, range: range) {
            attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
        }
        return attributedString
    } catch {
        NSLog("Error creating regular expresion: \(error)")
        return nil
    }
}

到目前为止你看了什么?属性字符串?显示你当前的code@Wain不,我还没有做任何事情。但是在objective c中看到了属性字符串的代码。无法理解。你能帮我解决这个可能的@Anbu.Karthik副本吗?它没有详细说明answer@GaneshKumar编辑我的答案。我使用谓词进行筛选。我应该在何处使用代码..在筛选器中?还是在CellForRowatineXpath中?@GaneshKumar如果您使用表视图呈现搜索结果,则必须将其用作
CellForRowatineXpath
@GaneshKumar如果我的答案有用,请接受它。让我们节约我的一天..=D
  private func boldedString(with baseString: String, searchString: String, fontSize: CGFloat) -> NSAttributedString? {
    guard let regex = try? NSRegularExpression(pattern: searchString, options: .caseInsensitive) else {
        return nil
    }

    let attributedString = NSMutableAttributedString(string: baseString)
    let boldFont = UIFont.systemFont(ofSize: fontSize, weight: .bold)
    regex
      .matches(in: baseString, options: .withTransparentBounds,
               range: NSRange(location: 0, length: baseString.utf16.count))
      .forEach {
        attributedString.addAttributes([.font: boldFont], range: $0.range)
    }
    return attributedString
  }
func configure(with text: String, searchText: String?) {
  if let boldedAddress = boldedString(with: text,
                                      searchString: searchText,
                                      fontSize: titleLabel.font.pointSize) {
    titleLabel.attributedText = boldedAddress
  } else {
    titleLabel.text = locationInfo.location.address
  }
}
func generateAttributedString(with searchTerm: String, targetString: NSAttributedString) -> NSAttributedString? {
    let attributedString = NSMutableAttributedString(attributedString: targetString)
    do {

        let regex = try NSRegularExpression(pattern:  NSRegularExpression.escapedPattern(for: searchTerm).trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .regularExpression, locale: .current), options: .caseInsensitive)
        let range = NSRange(location: 0, length: targetString.string.utf16.count)
        attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: range)


        for match in regex.matches(in: targetString.string.folding(options: .regularExpression, locale: .current), options: .withTransparentBounds, range: range) {
            attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
        }
        return attributedString
    } catch {
        NSLog("Error creating regular expresion: \(error)")
        return nil
    }
}