Post

UIKit - NSRange란?

UIKit - NSRange란?

정확한 구분은 Foundation으로 분류하는게 맞지만, UIKit에서 주로 사용하기 때문에 UIKit으로 분류함.

image

NSRange는 문자열이나 배열처럼 연속된 데이터에서 특정 구간을 표현할 때 쓰이는 구조체임.

아래와 같은 두 가지 프로퍼티를 제공함.

image

  • location: 범위에서 첫 번째 요소의 인덱스
  • length: 범위 길이

UITextField Delegate 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// MARK: - TextField Delegate
extension TodoAddViewController: UITextFieldDelegate{
    
    ...
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        ...
        
        // 변경된 문자열의 수를 의미함.
        print("range : \(range.length)")

        // 현재 커서의 시작 위치를 의미함.
        print("location : \(range.location)")

        ...
    }
}

NSRange 구조체 자체는 범위를 의미하며, 위 예시같은 상황에서는 UITextField에 입력되는 글자들의 범위를 표현하는데 사용함.

Reference

This post is licensed under CC BY 4.0 by the author.