Last active
July 20, 2017 19:28
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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