我有一个tableview。 tableview的目的是显示源自UISearchBar用户输入的搜索结果。 tableview有一个自定义的tableview单元格,其中有一个Label和UITextView。函数传递用户搜索文本,将所述搜索文本与某些基本文本匹配,并使用特定字体,字体颜色和大小仅匹配匹配的文本。它用于突出显示匹配的字符,以便app用户可以在tableview单元格的Label和UITextView中查看搜索文本。值得注意的是,Label和UITextView的基本字体在IB中设置。匹配的搜索文本字体,颜色和大小通过上面引用的函数设置。
执行时,一切都与Label中出现的文本完美配合。匹配的搜索文本将根据需要更改为颜色,文本和大小,并且不匹配的文本保持不变。
后者不是UITextView中显示的文本的情况。匹配的搜索文本的颜色,大小和字体按预期更改。例如,如果应用用户输入""进入UISearchBar,"" UITextView中显示的具有预期的文本颜色,字体类型和大小更改。但是,UITextView中的文本字体(不匹配的文本)会更改为完全不同的字体。 (编辑 - 我原来的帖子说匹配和不匹配没有改变)。对于不匹配的文本,文本被更改为与IB中设置的任何内容完全不同的字体类型或通过函数设置的字体类型,字体大小很小。尽管我在修修补补,但字体类型和大小似乎是不可变的。
以下是应用于UITextView对象的代码:
// class function used to match search text and set attribute
class func attributeSearchedText (searchString: String, baseString: String) -> NSMutableAttributedString {
let attributedString:NSMutableAttributedString = NSMutableAttributedString(string: baseString)
let regex = try! NSRegularExpression(pattern: searchString, options: .caseInsensitive)
for match in regex.matches(in: baseString, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: (baseString.characters.count))) as [NSTextCheckingResult]
{
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: match.range)
attributedString.addAttribute(NSFontAttributeName, value: UIFont(name:"HelveticaNeue-Bold", size: 14.0)!, range: match.range)
}
return attributedString
}
// function applied to the tableview cell
cell.ruleTextBody.attributedText = SearchObject.attributeSearchedText2(searchString: searchString, baseString: filteredData[indexPath.row].ruleTxtBody)
如果我删除了belongsText函数,那么最初在IB中设置的字体将按预期显示:
cell.ruleTextBody.text = filteredData[indexPath.row].ruleTxtBody
鉴于上述情况,很明显该问题与attributionText和UITextView有关。我需要UITextView,因为我想保留滚动功能。
有关如何解决此问题的任何想法?
答案 0 :(得分:1)
因为您忘记设置非突出显示文本的属性。如果您没有指定,NSAttributedString
将默认为12pt系统字体(旧金山适用于iOS 10 / Helvetica)。
试试这个:
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var defaultAttributes: [String: Any]!
override func viewDidLoad() {
super.viewDidLoad()
// This is how you designed the text view in IB
self.defaultAttributes = textView.attributedText.attributes(at: 0, effectiveRange: nil)
self.textView.attributedText = ViewController.attributeSearchedText(searchString: "a", baseString: self.textView.text, defaultAttributes: self.defaultAttributes)
}
class func attributeSearchedText (searchString: String, baseString: String, defaultAttributes: [String: Any]) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: baseString, attributes: defaultAttributes)
let regex = try! NSRegularExpression(pattern: searchString, options: .caseInsensitive)
for match in regex.matches(in: baseString, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: (baseString.characters.count))) as [NSTextCheckingResult]
{
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: match.range)
attributedString.addAttribute(NSFontAttributeName, value: UIFont(name:"HelveticaNeue-Bold", size: 14.0)!, range: match.range)
}
return attributedString
}
}
结果:
如果您的文字位于UITableView
内并且不需要可编辑性,则使用UILabel
代替UITextView
来保存文字内容会更有效。自定义表格单元格的一个示例(记得将UILabel
放入原型单元格并从Interface Builder连接插座)
import UIKit
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var contentLabel: UILabel!
class func attributeSearchedText (searchString: String, baseString: String, defaultAttributes: [String: Any]?) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: baseString, attributes: defaultAttributes)
let regex = try! NSRegularExpression(pattern: searchString, options: .caseInsensitive)
for match in regex.matches(in: baseString, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: (baseString.characters.count))) as [NSTextCheckingResult]
{
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: match.range)
// You may consider dropping this line so that it uses whatever you designed in IB
// attributedString.addAttribute(NSFontAttributeName, value: UIFont(name:"HelveticaNeue-Bold", size: 14.0)!, range: match.range)
}
return attributedString
}
}
视图控制器:
class ViewController: UITableViewController {
var defaultAttributes: [String: Any]?
let cellContents = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer pulvinar velit ut dignissim iaculis. Vivamus sit amet justo auctor, fermentum nunc quis, facilisis odio. Nullam vitae tempor diam. Aliquam ultrices bibendum cursus. Fusce non est eros. In aliquet viverra dui, sed porttitor magna dignissim volutpat. Etiam aliquam mauris ut ligula feugiat finibus",
"Sed efficitur ut nunc in vehicula. Duis fringilla, ligula vel lacinia commodo, mauris dui consectetur dui, egestas rhoncus nulla justo sit amet elit. Sed sollicitudin iaculis mi, eu commodo libero dictum ac. Morbi lobortis aliquet quam ac egestas. In in suscipit eros. Vivamus vel mauris pretium, sollicitudin mi nec, iaculis elit. Mauris venenatis ullamcorper elementum. Aenean in sapien vel felis venenatis placerat.",
"Fusce placerat vestibulum massa quis congue. Mauris rutrum sagittis pellentesque. Integer pulvinar a massa vel mattis. Duis vehicula porta nibh, nec gravida dui. Sed facilisis, nisi in efficitur tempus, nibh ex rutrum purus, eu volutpat lorem dui nec neque. Curabitur et iaculis turpis. Vivamus cursus massa quis tincidunt pellentesque. Nunc interdum justo eu viverra dictum. Nulla quis sagittis dui, vel hendrerit diam. Duis vel fermentum neque, sit amet euismod sapien. Curabitur sagittis justo vitae feugiat feugiat. Nullam nunc magna, convallis vel dui in, fringilla lacinia nibh. Aenean euismod commodo est, at congue felis."
]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44
if let cell = self.tableView.dequeueReusableCell(withIdentifier: "myCell") as? MyTableViewCell {
self.defaultAttributes = cell.contentLabel.attributedText?.attributes(at: 0, effectiveRange: nil)
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cellContents.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! MyTableViewCell
cell.contentLabel.attributedText = MyTableViewCell.attributeSearchedText(searchString: "a", baseString: cellContents[indexPath.row], defaultAttributes: self.defaultAttributes)
return cell
}
}