2016-10-10 7 views
0

Lorsque l'utilisateur appuie sur la touche [Retour], il doit afficher le numéro. Comme les numéros de série [1,2 etc] pour chaque ligne. Y a-t-il un moyen de le faire?Comment faire la numérotation automatique sur UITextview lorsque vous appuyez sur la touche de retour dans swift

code suivant j'ai essayé

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { 

    var textview_text_nssring = textView.text as NSString 




    // Add "1" when the user starts typing into the text field 


    if (range.location == 0 && textView.text.isEmpty) { 


     if text == "\n" { 

      textView.text = "1." 

      let cursor = NSMakeRange(range.location + 3, 0) 
      textView.selectedRange = cursor 
      return false 
     } 

     else { 

      textView.text = NSString(format: "1. %@", text) as String 
     } 


    } 




return true 

} 
+0

Montrez-nous ce que vous avez essayé. –

+0

@NiravD updated.thanks – Lydia

Répondre

1

Déclarer un Int var pour le numéro de ligne en cours et de l'utiliser à l'intérieur comme shouldChangeTextIn range cette façon.

var currentLine: Int = 1 

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { 
    // Add "1" when the user starts typing into the text field 
    if (textView.text.isEmpty && !text.isEmpty) { 
     textView.text = "\(currentLine). " 
     currentLine += 1 
    } 
    else { 
     if text.isEmpty { 
      if textView.text.characters.count >= 4 { 
       let str = textView.text.substring(from:textView.text.index(textView.text.endIndex, offsetBy: -4)) 
       if str.hasPrefix("\n") { 
        textView.text = String(textView.text.characters.dropLast(3)) 
        currentLine -= 1 
       } 
      } 
      else if text.isEmpty && textView.text.characters.count == 3 { 
       textView.text = String(textView.text.characters.dropLast(3)) 
       currentLine = 1 
      } 
     } 
     else { 
      let str = textView.text.substring(from:textView.text.index(textView.text.endIndex, offsetBy: -1)) 
      if str == "\n" { 
       textView.text = "\(textView.text!)\(currentLine). " 
       currentLine += 1 
      } 
     } 

    } 
    return true 
} 
+0

Merci.Mais ce code ne gère pas retour arrière. Si nous frappons retour arrière même augmenter le numéro – Lydia

+0

@Lydia Vérifiez la réponse éditée pour réduire le numéro de ligne lorsque vous supprimez. –

+0

A travaillé parfait.Il gère également l'édition du texte précédent – Lydia