Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Last active October 11, 2023 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielt1263/2a1149da3fadd40c213c31aece3b948d to your computer and use it in GitHub Desktop.
Save danielt1263/2a1149da3fadd40c213c31aece3b948d to your computer and use it in GitHub Desktop.
//
// UITextViewExtensions.swift
//
// Created by Daniel Tartaglia on 7/20/17.
// Copyright © 2017 Daniel Tartaglia. MIT License.
//
import UIKit
extension UITextField {
func set(text newText: String, preservingCursor: Bool) {
if preservingCursor {
let cursorPosition = offset(from: beginningOfDocument, to: selectedTextRange!.start) + newText.count - (text?.count ?? 0)
text = newText
if let newPosition = position(from: beginningOfDocument, offset: cursorPosition) {
selectedTextRange = textRange(from: newPosition, to: newPosition)
}
}
else {
text = newText
}
}
func set(attributedText newText: NSAttributedString, preservingCursor: Bool) {
if preservingCursor {
let cursorPosition = offset(from: beginningOfDocument, to: selectedTextRange!.start) + newText.string.count - (attributedText?.string.count ?? 0)
attributedText = newText
if let newPosition = position(from: beginningOfDocument, offset: cursorPosition) {
selectedTextRange = textRange(from: newPosition, to: newPosition)
}
}
else {
attributedText = newText
}
}
}
extension UITextView {
func set(text newText: String, preservingCursor: Bool) {
if preservingCursor {
let cursorPosition = offset(from: beginningOfDocument, to: selectedTextRange!.start) + newText.count - (text?.count ?? 0)
text = newText
if let newPosition = position(from: beginningOfDocument, offset: cursorPosition) {
selectedTextRange = textRange(from: newPosition, to: newPosition)
}
}
else {
text = newText
}
}
func set(attributedText newText: NSAttributedString, preservingCursor: Bool) {
if preservingCursor {
let cursorPosition = offset(from: beginningOfDocument, to: selectedTextRange!.start) + newText.string.count - (attributedText?.string.count ?? 0)
attributedText = newText
if let newPosition = position(from: beginningOfDocument, offset: cursorPosition) {
selectedTextRange = textRange(from: newPosition, to: newPosition)
}
}
else {
attributedText = newText
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment