2016-10-10 3 views
0

[Return] 키를 누르면 번호가 표시됩니다. 각 줄에 대한 일련 번호 [1,2 etc]를 좋아해. 그럴 수있는 방법이 있니?신속한 반환 키를 누를 때 UITextview에서 자동 번호 매기기를 만드는 방법

다음 코드는 내가 현재 행 번호를 하나 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