Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] NSRange 개념 (location, length) 본문

iOS 응용 (swift)

[iOS - swift] NSRange 개념 (location, length)

jake-kim 2023. 10. 28. 00:12

NSRange 개념

  • 연속된 것 중 한 부분을 나타내는 개념
    • NSRange는 _NSRange의 별칭

https://developer.apple.com/documentation/foundation/nsrange

  • location과 length 2가지의 stored property만 있으면 연속된 것 중 한 부분을 나타낼 수 있음
    • location: 연속된 길이 중 한 지점
    • length: 길이
public struct _NSRange : @unchecked Sendable {

    public init()

    public init(location: Int, length: Int)

    public var location: Int

    public var length: Int
}
  • extension으로 여러가지 프로퍼티와 메서드도 제공
    • 주로 범위를 비교할 때 사용하는 연산자
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension _NSRange {

    @inlinable public var lowerBound: Int { get }

    @inlinable public var upperBound: Int { get }

    @inlinable public func contains(_ index: Int) -> Bool

    @inlinable public mutating func formUnion(_ other: NSRange)

    @inlinable public func union(_ other: NSRange) -> NSRange

    @inlinable public func intersection(_ other: NSRange) -> NSRange?
}

NSRange 예제) shouldChangeTextIn

  • UITextViewDelegate를 준수하면 shouldChangeTextIn 메서드에서 range를 제공
textView.delegate = self

extension ViewController: UITextViewDelegate {
    func textView(
        _ textView: UITextView,
        shouldChangeTextIn range: NSRange,
        replacementText text: String
    ) -> Bool {
        print("location", range.location)
        print("length", range.length)
        return true
    }
}
  • location에서는 현재 커서의 시작 위치를 알려주고, length는 변경된 문자열의 개수를 의미
  • 만약 "abcd"라는 문자열에서 c오른쪽에 커서가 있을때 공백 " "을 입력한 경우?
    • location = 3
    • length = 0

  • 주의할 점0): shouldChangeTextIn 메서드에서 받는 range는 텍스트가 변경된 후의 값을 의미
  • 주의할 점1): "abc"문자열이 있을 때 location 값은 a왼쪽, a오른쪽 을 의미하는게 아니라 커서의 시작 위치를 의미
    • 공백에 "a" 입력하면 location 값이 0 (커서의 시작 위치는 인덱스 0번인 공백 위치였으므로)
    • "ab"에서 b를 backspace로 지우면 location 값이 1 (커서의 시작위치는 인덱스 1번인 b위치였으므로)

(결과만 봤을 때 커서의 위치는 A 뒷쪽으로 동일하지만 location값은 커서의 시작 위치에 따라 달라짐)

* cf) 더 읽어보면 좋은 글 - NSRange와 함께 Cursor 개념 알아보는 포스팅 글

 

* 전체 코드: https://github.com/JK0369/ExRange

* 참고

https://developer.apple.com/documentation/foundation/nsrange

Comments