我有一个UITextField和UIButton来执行搜索:
oParentNode
在按下UIButton时,会调用一个函数来搜索UITextView中UITextFiled中给出的单词:
@IBOutlet weak var searchcodetxt: UITextField!
@IBOutlet weak var searchcodebtn: UIButton!
但是当我点击搜索按钮时,它没有为特定单词着色。如何纠正这个?
答案 0 :(得分:0)
您的代码中需要进行一些更改才能使其生效。
在searchCode()
函数中,let range = match.rangeAtIndex(1)
会导致索引超出范围的应用程序崩溃。
您只需使用match.range添加属性:
if let match = matches.first {
attributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: match.range)
}
只需更正此行即可使您的代码正常工作,但这将仅突出显示文本视图中的第一个匹配项。
要突出显示所有匹配,您可以更改此块
if let match = matches.first {
let range = match.rangeAtIndex(1)
if let swiftRange = rangeFromNSRange(range, forString: baselowercase) {
attributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: match.range)
}
}
并在matches数组上添加一个循环,迭代所有匹配并添加一个属性以突出显示它们。
for match in matches {
attributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: match.range)
}
searchCode()
的完整代码将是:
func searchCode(){
let keyword = self.searchcodetxt.text
let lowercasekeyword = keyword!.lowercaseString
let baseString = webcode.text
let baselowercase = baseString!.lowercaseString
let attributed = NSMutableAttributedString(string: baseString)
do {
let regex = try NSRegularExpression(pattern: lowercasekeyword, options: NSRegularExpressionOptions.CaseInsensitive)
let matches = regex.matchesInString(baselowercase, options: [], range: NSMakeRange(0, baselowercase.characters.count))
for match in matches {
attributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: match.range)
}
webcode.attributedText = attributed
} catch {
// regex was bad!
let alertView:UIAlertView = UIAlertView()
alertView.title = "Keywords error!"
alertView.message = "Please use another keywords"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
// Delay the dismissal by 5 seconds
let delay = 5.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
alertView.dismissWithClickedButtonIndex(-1, animated: true)
})
}
}
现在,您不需要rangeFromNSRange()
方法。