Last active
October 11, 2023 10:18
-
-
Save danielt1263/2a1149da3fadd40c213c31aece3b948d to your computer and use it in GitHub Desktop.
This file contains 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
// | |
// 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