ios - NSRegularExpression, matching strings, and highlighting text. Works about 85% of the time. Why? -
part of app i'm working on takes string, looks in textfield , highlights string. works 85% of time. other 15% app behaves if highlighted text text isn't highlighted. no errors.
there no way strings (in textfield , 1 compared) different because same source.
any idea why highlight attribute isn't applied when should be?
let attributed = nsmutableattributedstring(string: completetext) var error: nserror? let regex = nsregularexpression(pattern: comparestring, options: .caseinsensitive, error: &error) if let regexerror = error { println("oh no! \(regexerror)") } else { println("highlighted") match in regex?.matchesinstring(completetext, options: nsmatchingoptions.allzeros, range: nsrange(location: 0, length: count(completetext))) as! [nstextcheckingresult] { attributed.addattribute(nsbackgroundcolorattributename, value: uicolor.yellowcolor(), range: match.range) } } completetext.text = completetext // view receiving text completetext.attributedtext = attributed //apply highlighting
your final lines of code confusing, assigning completetext completetext.text making unclear whether completetext instance string or uitextview. assigning .text , .attributedtext, isn't necessary. .text available automatically when set .attributedtext property , has same value attributed.string. therefore need set .attributedtext not .text.
cleaning things works.
let completetext = "hello world, you? you?" let comparestring = "hello world, you\\? you\\?" let attributed = nsmutableattributedstring(string: completetext) var error: nserror? let regex = nsregularexpression(pattern: comparestring, options: .caseinsensitive, error: &error) if let regexerror = error { println("oh no! \(regexerror)") } else { println("highlighted") match in regex?.matchesinstring(completetext, options: nsmatchingoptions.allzeros, range: nsrange(location: 0, length: count(completetext))) as! [nstextcheckingresult] { attributed.addattribute(nsbackgroundcolorattributename, value: uicolor.yellowcolor(), range: match.range) } } let textview = uitextview(frame: cgrect(x: 0, y: 0, width: 400, height: 200)) textview.attributedtext = attributed but you'll see example if characters in string have special meaning in regularexpression language, e.g. ?, .* , [], you'll need escape these find them in string.
see nsregularexpression class reference table of special characters.
Comments
Post a Comment