gpt4 book ai didi

ios - 无法将类型 'Range'(又名 'Range')的值转换为预期参数类型 'NSRange'(又名 '_NSRange')

转载 作者:搜寻专家 更新时间:2023-10-30 21:50:10 29 4
gpt4 key购买 nike

我正在尝试用属性字符串替换子字符串。以下是我的代码。

let searchText = self.searchBar.text!
let name = item.firstName ?? ""
let idNo = "Employee Id. \(item.employeeId ?? "NA")"

if let range = name.range(of: searchText, options: String.CompareOptions.caseInsensitive, range: nil, locale: nil)
{
let attributedSubString = NSAttributedString.init(string: name.substring(with: range), attributes: [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 17)])
let normalNameString = NSMutableAttributedString.init(string: name)
normalNameString.mutableString.replacingCharacters(in: range, with: attributedSubString)
cell.name.attributedText = normalNameString
}
else
{
cell.name.text = name
}

我遇到编译时错误:

"Cannot convert value of type 'Range' (aka 'Range') to expected argument type 'NSRange' (aka '_NSRange')".

我应该在这里更改什么?

最佳答案

您可以使用 NSStringNSRange,您还需要更改此行 normalNameString.mutableString.replacingCharacters(in: range, with: attributedSubString) 并改用这个 normalNameString.replaceCharacters(in: nsRange, with: attributedSubString) 因为 mutableString 是 NSMutableString,而 replacingCharacters 期望 String 和不是 NSAttributtedString

完整代码(针对 Swift5 更新)

    let nsRange = NSString(string: name).range(of: searchText, options: String.CompareOptions.caseInsensitive)

if nsRange.location != NSNotFound
{
let attributedSubString = NSAttributedString.init(string: NSString(string: name).substring(with: nsRange), attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17)])
let normalNameString = NSMutableAttributedString.init(string: name)
normalNameString.replaceCharacters(in: nsRange, with: attributedSubString)
cell.name.attributedText = normalNameString
}
else
{
cell.name.text = name
}

关于ios - 无法将类型 'Range<String.Index>'(又名 'Range<String.CharacterView.Index>')的值转换为预期参数类型 'NSRange'(又名 '_NSRange'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46232072/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com