2017-04-11 4 views
0

사용자가 UITextView에 입력 한 정보 중에서 번호 매기기 목록을 만들려고합니다. 예를 들어,UITextView Swift 3에서 번호 매기기 목록 만들기

  1. 목록 항목 하나 개
  2. 목록 항목이
  3. 목록의 항목을 다음 세 가지

내가 시도했지만 나에게 원하는 효과를 제공하지 않는 코드입니다. var에 currentLine : 지능 여기 제안 = 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 
} 

: How to make auto numbering on UITextview when press return key in swift는하지만 성공이 없었다.

도움을 주시면 감사하겠습니다.

답변

0

당신은 UITextView, 재정의 메서드 willMove (toSuperview를 서브 클래스와 열거하고 그에 따라 그것을 번호 라인에 텍스트를 헤어 선택기로 UITextViewTextDidChange에 대한 관찰자를 추가 할 수 있습니다 다음과 같이 시도해보십시오.

class NumberedTextView: UITextView { 
    override func willMove(toSuperview newSuperview: UIView?) { 
     frame = newSuperview?.frame.insetBy(dx: 50, dy: 80) ?? frame 
     backgroundColor = .lightGray 
     NotificationCenter.default.addObserver(self, selector: #selector(textViewDidChange), name: .UITextViewTextDidChange, object: nil) 
    } 
    func textViewDidChange(notification: Notification) { 
     var lines: [String] = [] 
     for (index, line) in text.components(separatedBy: .newlines).enumerated() { 
      if !line.hasPrefix("\(index.advanced(by: 1))") && 
       !line.trimmingCharacters(in: .whitespaces).isEmpty { 
       lines.append("\(index.advanced(by: 1)). " + line) 
      } else { 
       lines.append(line) 
      } 
     } 
     text = lines.joined(separator: "\n") 
     // this prevents two empty lines at the bottom 
     if text.hasSuffix("\n\n") { 
      text = String(text.characters.dropLast()) 
     } 
    } 
} 

import UIKit 

class ViewController: UIViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     let textView = NumberedTextView() 
     view.addSubview(textView) 
    } 
} 
+0

야, 정말 고마워. 이런 식으로 생각조차하지 않았다. 너 락! –

+0

@JacobE 환영합니다. –

+0

방금 ​​새로운 앱과 글 머리 기호 목록을 구현하려했지만 하나의 작품. 당신이 그것을 밖으로 확인하시기 바랍니다. s : //stackoverflow.com/q/45869927/7513942? sem = 2 –