8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UITextViewの使い勝手を少しだけ良くする

Last updated at Posted at 2018-03-06

UITextViewをそのまま使った場合,少し使い勝手が悪い点があるので,その対応についての備忘録を兼ねた小ネタです.

Paddingを消す

UITextViewはデフォルトでPaddingが設定されています.
Paddingも考慮してレイアウトを組むのは面倒なので, viewDidLoad() などに以下のコードを追加し,Paddingを消去します.

textView.textContainerInset = UIEdgeInsets.zero
textView.textContainer.lineFragmentPadding = 0

全選択を可能にする

isEditable == false の場合,ロングタップ時のメニューに全選択がありません.
以下のように canPerformAction() をオーバライドして,メニューをカスタマイズします.
なお,分岐条件に action == #selector(select(_:)) を追加してメニューに「選択」を表示することもできますが,そのアクションをタップしても選択範囲は変わらず特に何の変化も及ぼさないので,今回は除外しました.

class AllSelectableTextView: UITextView {
        
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        
        // すべて選択,コピー,共有のみ利用可能
        if action == #selector(selectAll(_:)) ||
            action == #selector(copy(_:)) ||
            action == Selector(("_share:")) {
            return true
        } else {
            return false
        }
    }
}

UITextViewを編集不可にして表示するような場合,ある程度長いテキストを表示することが想定されます.
全選択(からのコピーや共有)を容易にすることで,細かなユーザビリティの改善にも繋がるかと思います.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?