ios - Detecting empty lines and absence of text in a UITextView in Swift -
i have created uitextview programmatically , , added placeholder so:
//textview textview.frame = cgrectmake(viewsize.width * 0.05, contentview.frame.height - viewsize.width * 0.05, viewsize.width - viewsize.width * 0.05 * 2, -viewsize.height * 0.220833) self.textview.delegate = self self.textview.text = "agregue una descripciĆ³n..." self.textview.textcolor = uicolor.lightgraycolor() self.textview.autocorrectiontype = uitextautocorrectiontype.no self.textview.layer.cornerradius = 6 self.view.addsubview(textview)
and in delegate functions:
func textviewdidbeginediting(textview: uitextview) { if textview.textcolor == uicolor.lightgraycolor() { textview.text = "" textview.textcolor = uicolor.blackcolor() } } func textviewdidendediting(textview: uitextview) { if textview.text.isempty { textview.text = "agregue una descripciĆ³n..." textview.textcolor = uicolor.lightgraycolor() } }
i have tried check string text nil:
if textview.text == nil
and this:
if textview.text == ""
none did detected empty lines, , nil comparison not detecting absence of text after adding , deleting chars.
so when user enters text there no problem, , when user deletes text placeholder comes back, if add line or more without text, comparison empty not true, need way detect have no text , lines added not have text, because newly introduced in swift .isempty
not detecting empty lines added, nor of other comparison did.
how can detect empty lines in string?
ask whether text composed of characters nscharacterset whitespaceandnewlinecharacterset
(or whatever characters constitute emptiness in mind - perhaps after newlinecharacterset
). easiest way take invertedset
, call rangeofcharacterfromset
- if result {nsnotfound, 0}
(swift nil
), text is composed of whitespace characters.
extension string { var isblank : bool { let s = self let cset = nscharacterset.newlinecharacterset().invertedset let r = s.rangeofcharacterfromset(cset) let ok = s.isempty || r == nil return ok } } "howdy".isblank // false "".isblank // true "\n\n".isblank // true
Comments
Post a Comment