Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Last active July 20, 2017 19:28
Show Gist options
  • Save danielt1263/cacfd3f7cd55adfe4cedba990d751d38 to your computer and use it in GitHub Desktop.
Save danielt1263/cacfd3f7cd55adfe4cedba990d751d38 to your computer and use it in GitHub Desktop.
Allows you to set the text in a UITextField *without* changing the position of the cursor.
//
// UITextField+Extensions.swift
//
// Created by Daniel Tartaglia on 8/8/16.
// Copyright © 2016 MIT License.
//
import UIKit
extension UITextField {
func setText(to newText: String, preservingCursor: Bool) {
if preservingCursor {
let cursorPosition = offset(from: beginningOfDocument, to: selectedTextRange!.start) + newText.characters.count - (text?.characters.count ?? 0)
text = newText
if let newPosition = position(from: beginningOfDocument, offset: cursorPosition) {
selectedTextRange = textRange(from: newPosition, to: newPosition)
}
}
else {
text = newText
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment