Create a title from the first line of a UITextView (Think Apple Notes) Swift

I am trying to set the title of my notes using the first line from a UITextView. Only the last section of my code does not work.

(If you are wondering why I use "else" in addition to the 30-character expression, because if I do not put a note with at least 30 characters, there is an error)

override func viewWillDisappear(animated: Bool) { detailItem!.noteText = self.textView.text if !self.textView.text.isEmpty { var textViewString:String = self.textView.text if let range = self.textView.text.rangeOfString("\n") { let rangeOfString = self.textView.text.startIndex ..< range.endIndex let firstLine = self.textView.text.substringWithRange(rangeOfString) detailItem?.noteTitle = firstLine } else { // take up to the first 30 characters as the title let length = count(self.textView.text) if length > 30 { let firstLine = (textView.text as NSString).substringFromIndex(30) detailItem?.noteTitle = firstLine } else { let firstLine = (textView.text as NSString).substringFromIndex(length) detailItem?.noteTitle = firstLine } } } 

So a code that doesn't work is the last part:

  } else { let firstLine = (textView.text as NSString).substringFromIndex(length) detailItem?.noteTitle = firstLine } 

Questions:

1) What is the difference between plain old int and variable, what is int?

2) What is the work to achieve the same result if my method is not possible?

+4
source share
2 answers

Use .substringToIndex () instead of .substringFromIndex () and you will get the correct result.

+2
source

I had the same problem and I found this method that works very well. You have an explanation in the code comments:

 //If it empty will return this values if self.txtText.text.isEmpty { title = "(Empty Note)" texto = "(Empty Note)" } //If it not... else { //We provide the value "\n" to say which will be te last character let till: Character = "\n" if let idx = texto.characters.indexOf(till) { //Get the position of this character let pos = texto.startIndex.distanceTo(idx) //Substract 1 to not add the \n to the title firstLine = (txtText.text as NSString).substringToIndex(pos-1) } else { //If it longer than 30 chars, get 30 if texto.characters.count >= 30{ firstLine = (txtText.text as NSString).substringToIndex(30) } //If it shorter, count the chars and get till the last of this line else{ firstLine = (txtText.text as NSString).substringToIndex(texto.characters.count) } } title = firstLine } 
+1
source

All Articles