Swift

UITextView - 현재 커서 위치 가져오기

진태우 2018. 4. 5. 19:46

현재 커서의 앞과 뒤의 텍스트를 나누는 방법을 알고 싶었다.

그러기 위해서는 현재 커서의 위치를 가져오는게 선행되어야 했다.

let textRange = textView.selectedTextRange
print("\(textRange)")      // <_UITextKitTextRange: 0x1c443c600> (5, 0)B

위 코드는 커서 위치를 가져오는 코드이다.

그럼 위치를 이용해서 해당 위치의 전과 후의 텍스트를 가져오는 로직을 구현하면 된다.

let textString = textView.text!
let textRange = textView.selectedTextRange!
let offset = textView.offset(from: textView.beginningOfDocument, to: textRange.start)

// 커서 앞에 위치한 텍스트
let beforeString = textString.substring(to: textString.index(textString.startIndex, offsetBy: offset))

// 커서 뒤에 위치한 텍스트
let afterString = textString.substring(from: textString.index(textString.startIndex, offsetBy: offset))


아래는 텍스트의 끝에 커서를 위치하는 코드이다.

자신이 원하는 곳에 커서를 위치하고 싶을 때 사용하면 될 것 같다.

let position = textView.endOfDocument
textView.selectedTextRange = textView.textRange(from:position, to:position)