Notice
Recent Posts
Recent Comments
Link
관리 메뉴

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

[iOS - swift] UITextView의 cursor 다루기 (NSRange, location, length) 본문

iOS 응용 (swift)

[iOS - swift] UITextView의 cursor 다루기 (NSRange, location, length)

jake-kim 2023. 10. 29. 01:44

UITextView의 Cursor 개념

  • Cursor는 사용자 편의를 위해서 현재 수정되거나 작성될 곳의 위치를 나타내는 역할

cursor

  • 애플에서는 이 Cursor도 코드로 이동시키거나 Cursor의 위치를 파악할 수 있도록 NSRange 형태로 제공
  • NSRange 요약 개념
    • NSRange는 _NSRange의 Typealias로 되어 있고 범위의 시작 위치를 location, 길이를 length 프로퍼티로 표현
public struct _NSRange : @unchecked Sendable {

    public init()

    public init(location: Int, length: Int)

    public var location: Int

    public var length: Int
}

@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?
}
  • 여기서 extension으로 구현된 lowerBound, upperBound는 UITextView의 커서 정보를 유용하게 제공

NSRange와 함께 UITextView의 cursor 알아보기

  • cursor 현재 드래그하고 있는 커서의 위치가 첫번째인지 두번째인지 판단하는 방법
    • lowerBound: 첫번째 커서의 위치 (아래 예제에서의 값 = 14)
    • upperBound: 두번째 커서의 위치 (아래 예제에서의 값 = 20)

2가지의 커서 판단

  • cursor 겹쳐있는지 유무 판단
    • lowerBound와 upperBound가 같은 경우
    • 모두 20으로 값 동일

 

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

Comments