LoginSignup
9
6

More than 5 years have passed since last update.

【Swift】UITextViewでキャレットの位置を現在の位置から任意数分移動させる

Last updated at Posted at 2015-08-07

Swiftでのキャレット操作の記事が見つからなかったのでメモ

キャレット位置を現在の位置から指定分ずらすメソッドを拡張してみた。

UITextView+CaretExtension.swift
import UIKit

extension UITextView {

    /**
    現在のキャレットの位置をoffset分ずらす

    :param: offset Int ずらす量 

    :returns: bool 成功か失敗 
    */
    func changeCaret(offset:Int) -> Bool {

        // 全角文字を確定状態にする
        let nowText = self.text
        self.text = nowText

        if let range = self.selectedTextRange {
            let position = self.positionFromPosition(range.start, offset: offset)

            self.selectedTextRange = self.textRangeFromPosition(position, toPosition: position)

            return true
        }

        return false
    }
}

使い方

ViewController
// 4つ分前の位置にキャレットを持っていく
textView.changeCaret(-4)

boolで返す必要ないか?

9
6
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
9
6