我正在使用“UITextField”作为搜索框的应用程序中工作。当用户在带有部分的 uitextfield UiTableView 中输入搜索文本时将显示结果,但我需要突出显示在 tableview 的文本字段中输入的文本。我使用了属性文本,但它只能在一个范围内使用。所以请帮我一个实现荧光笔的想法。
myMutableString = NSMutableAttributedString(string: contactsList.familyName + contactsList.givenName, attributes: [NSAttributedStringKey.font:UIFont(name: "Catamaran", size: 14.0)!])
if contactsList.familyName.count >= 4 {
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black, range: NSRange(location:0,length:4))
}else {
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black, range: NSRange(location:0,length:2))
}
cell?.profileName.attributedText = myMutableString
我试图改变前景色,但它只是改变文本颜色而不是背景颜色。我不知道这是否是正确的解决方案,但您可以尝试这样的方法。
如果我正确理解您的问题,则突出显示文本字段
全局添加标签
let label = UILabel()
在 viewDidLoad 中设置标签框架
label.frame.size = CGSize(width: 10, height: textfield.frame.size.height)// your settings width should be 10 or smaller
label.font = UIFont(name: "Halvetica", size: 14)
label.backgroundColor = UIColor.red
将文本字段文本颜色设置为文本字段背景颜色
textfield.textColor = UIColor.white
像这样添加 textFieldEditingChanged 方法:
@IBAction func changed(_ sender: Any) {
label.removeFromSuperview()
label.text = textfield.text
textfield.addSubview(label)
label.sizeToFit()
}
不要忘记将标签和文本字段字体设置为相同。如果不这样做,文本字段光标可能会出现在标签的后面或前面
更新:您应该使用 html 创建属性字符串
extension String {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8),
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}// you can find several way to do this just google it
}
数据源:
var dataSource = ["foo","foo1","foo2","foo3","foo4","foo5","foo6"]
为在数据源字符串范围内找到的结果索引创建变量
var indexes : [Int:Range<String.Index>] = [:]
cellForRowAt:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let string = dataSource[indexPath.row]
cell.textLabel?.attributedText = string.html2AttributedString
return cell
}
搜索文本编辑更改:
@IBAction func change(_ sender: UITextField) {
indexes.removeAll()
dataSource = ["foo","foo1","foo2","foo3","foo4","foo5","foo6"] // assign datasource again
for i in 0..<dataSource.count {
if let textRange = dataSource[i].range(of: textField.text!) {
indexes[i] = textRange
}
}
for (index,entry) in indexes {
let highlighted = "<text style='background-color:#FFFF00';>\(dataSource[index][entry])</text>"
dataSource[index].replaceSubrange(entry, with: highlighted)
}
tableView.reloadData()
}
希望这可以帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句