LoginSignup
4
1

More than 5 years have passed since last update.

Swift4: UITextViewのカーソル位置の前後のテキストを分割して取るExtension書いてみた

Posted at

仕様

  • カーソルがTextView上に存在しないとnil
  • テキストを選択していた場合、開始位置にカーソルがあると判断して分割する

コード

どうぞ。

import UIKit

extension UITextView {
    func splitTextsAtCursor() -> (left: String, right: String)? {
        guard let currentRange = self.selectedTextRange else {
            return nil
        }

        let currentPosition = currentRange.start
        guard let leftRange = self.textRange(from: self.beginningOfDocument, to: currentPosition), let leftText = self.text(in: leftRange) else {
            return nil
        }

        guard let rightRange = self.textRange(from: currentPosition, to: self.endOfDocument), let rightText = self.text(in: rightRange) else {
            return nil
        }

        return (left: leftText, right: rightText)
    }
}

textView.splitTextsAtCursor() // (left: "カーソルの左にある文字列", right: "カーソルの右にある文字列")
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1