2016-10-10 7 views
0

[戻る]キーを押して番号を表示する必要があります。シリアルナンバー[1、2など]と同じです。それを行う方法はありますか?すぐに戻るキーを押したときにUITextviewで自動番号を付ける方法

次のコードは、私は、現在の行番号を1つのInt VARを宣言し、この方法のようにshouldChangeTextIn range内で使用

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

お試しください。 –

+0

@NiravD updated.thanks – Lydia

答えて

1

を試してみました。

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

ありがとうございます。しかし、このコードはバックスペースを処理しません。バックスペースを押した場合でも数字を増やしてください。 – Lydia

+0

@Lydia削除したときに行番号を減らすために編集された答えを確認してください。 –

+0

完璧に働いています。前のテキストの編集も処理します – Lydia

関連する問題