How to replace string in particular range in iOS Swift? - ios

For example string = "Hello #manan123 and #man"
i am doing tagging functionality in textview and i want when user press backspace if word contains # then whole word will delete not single character.
but i am facing problem while two tagged word have same characters. So in above example when i am trying to delete last word #man then #manan123 also convert to the an123.
Here is my code on textview delegate method
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "" {
if let selectedRange = textView.selectedTextRange {
let cursorOffset = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
if let myText = textView.text {
let index = myText.index(myText.startIndex, offsetBy: cursorOffset)
let substring = myText[..<index]
if let lastword = substring.components(separatedBy: " ").last {
if lastword.hasPrefix("#") {
//Check complete word
let completeLastword = myText.components(separatedBy: " ").filter{$0.contains(lastword)}.last
textView.text = myText.replacingOccurrences(of: completeLastword!, with: "")
return false
}
}
}
}
}
return true
}

Hi I have updated your code please check it.
if text == "" {
if let selectedRange = textView.selectedTextRange {
let cursorOffset = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
if let myText = textView.text {
let index = myText.index(myText.startIndex, offsetBy: cursorOffset)
let substring = myText[..<index]
if let lastword = substring.components(separatedBy: " ").last {
if lastword.hasPrefix("#") {
var newText = myText
let start = newText.index(myText.startIndex, offsetBy: cursorOffset - lastword.count);
let end = newText.index(myText.startIndex, offsetBy: (cursorOffset - lastword.count) + lastword.count);
newText.replaceSubrange(start..<end, with: "")
textView.text = newText
return false
}
}
}
}
}
Hope this helps.

Related

Detect Cut operation in textfield - Swift

I have implemented the shouldChangeCharactersIn textfield delegate method. I have formatted the value in textfield so that textfield string becomes a comma separated currency type value. For that, I am explicitly handling the cursor to support conditions like inserting 2 commas at a time. The code used is :
let textBeforeEditing = textField.text!
if ((string == "0" || string == "") && (textField.text! as NSString).range(of: ".").location < range.location) {
return true
}
var currentPosition = 0
if let selectedRange = textField.selectedTextRange {
currentPosition = textField.offset(from: textField.beginningOfDocument, to: string == "" ? selectedRange.end : selectedRange.start)
}
let allowedCharacterSet = NSCharacterSet(charactersIn: "0123456789.").inverted
let filtered = string.components(separatedBy: allowedCharacterSet)
let component = filtered.joined(separator: "")
let isNumeric = string.replacingOccurrences(of: ",", with: "") == component
var textFieldString : String = ""
var numberWithoutCommas : String = ""
guard isNumeric else {
return false
}
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
textFieldString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
numberWithoutCommas = textFieldString.replacingOccurrences(of: ",", with: "")
let formattedNumberWithoutCommas = formatter.number(from: numberWithoutCommas)
guard let formattedNumber = formattedNumberWithoutCommas, var formattedString = formatter.string(from: formattedNumber) else {
textField.text = nil
return false
}
if string == "." && range.location == textField.text?.count {
formattedString = formattedString.appending(".")
}
var filteredRegex = [NSTextCheckingResult]()
filteredRegex = Constant.Regex.decimalRegex.matches(in: formattedString, options: [], range: NSMakeRange(0, formattedString.count))
guard filteredRegex.count == 1 else {
return false
}
textField.text = formattedString
currentPosition = getCursorPositionForTextField(string: string, cursorPosition: currentPosition, formattedString: formattedString, textBeforeEditing: textBeforeEditing)
handleTextFieldCursor(cursorPosition: currentPosition, textField: textField)
return false
So when I type 1234567890, it gets formatted to 1,234,567,890
The issue here is that when I cut any characters from textfield, I am unable to paste it anywhere else. I am unable to detect the reason why it isn't getting pasted. Please could someone help me out.
Is there any way to detect the cut operation for the same? Cut operation is getting overridden by the above code it seems.

Deleting word by word instead of character by character in textview ios

I have been trying to delete word by word that means If I have a sentence like "Hello, this #Sivajee is sample text", each time when I'm deleting 'e' letter in #Sivajee it should delete entire word #Sivajee from the sentence. I really have no clue about this.
Here is my code.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
let substring = (textView.text as NSString).substring(with: range)
//Tagging users
if text == "#" || substring == "#" || (isTagging && text == " "){
isTagging = !isTagging
searchTerm.removeAll()
tagSearchedUsers.removeAll()
tableView.reloadData()
}
else if isTagging {
searchTerm.append(text)
// to limit network activity, reload half a second after last key press.
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.getFriendsSearchResults), object: nil)
self.perform(#selector(self.getFriendsSearchResults), with: nil, afterDelay: 0.5)
}
return true;
}
On a whole, my idea is to tag someone while typing & deleting when a user uses backspace. Your input will be more valuable for me.
Edit:
The swift equivalent of proposed solution from comments not working
if (string == "") {
let selectedRange: UITextRange? = textField.selectedTextRange
let cursorOffset: Int = textField.offset(from: 0, to: (selectedRange?.start)!)
let text: String? = textField.text
let substring: String? = (text as? NSString)?.substring(to: cursorOffset)
let lastWord = substring?.components(separatedBy: " ")?.last as? String
if lastWord?.hasPrefix("#") ?? false {
// Delete word
textField.text = self.textField?.text()?.replacingOccurrences(of: lastWord!, with: "")
return false
}
}
Swift 4:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
if text == ""
{
if let selectedRange = textView.selectedTextRange
{
let cursorOffset = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
if let myText = textView.text
{
let index = myText.index(myText.startIndex, offsetBy: cursorOffset)
let substring = myText[..<index]
if let lastword = substring.components(separatedBy: " ").last
{
if lastword.hasPrefix("#")
{
//Check complete word
let completeLastword = myText.components(separatedBy: " ").filter{$0.contains(lastword)}.last
textView.text = myText.replacingOccurrences(of: completeLastword!, with: "")
return false
}
}
}
}
}
return true
}
Here is the Swift version of the proposed answer by commenters.
if (text == "") {
let selectedRange: UITextRange? = textView.selectedTextRange
let cursorOffset: Int = textView.offset(from: textView.beginningOfDocument, to: (selectedRange?.start)!)
let text: String? = textView.text
let substring: String? = (text as NSString?)?.substring(to: cursorOffset)
let lastWord = substring?.components(separatedBy: " ").last
print(lastWord)
if lastWord?.hasPrefix("#") ?? false {
// Delete word
textView.text = textView.text?.replacingOccurrences(of: lastWord!, with: "")
return false
}
}
But still it has draw back of, when deleting word from the middle it will delete only portion of it. Not entire word. That means, If I have word #Sivajee, If I put my cursor at letter 'V' and backspace, it will only delete #Siv. Not ajee also.

Dynamically format a number to have commas in a UITextField

How to format the price textfield text as a currency format like 234,345,567 and also I need to restrict the decimal points to not more than 2 and also to append $ symbol when user starts typing.
for example : $234,345,678.25
like this I want to add comma between 3numbers when they type the amount in textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if ((string == "0" || string == "") && (txtFldPostalCode.text! as NSString).range(of: ".").location < range.location) {
return true
}
let cs = NSCharacterSet(charactersIn: "0123456789.").inverted
let filtered = string.components(separatedBy: cs)
let component = filtered.joined(separator: "")
let isNumeric = string == component
if isNumeric {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 8
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let numberWithOutCommas = newString.replacingOccurrences(of: ",", with: "")
let number = formatter.number(from: numberWithOutCommas)
if number != nil {
var formattedString = formatter.string(from: number!)
if string == "." && range.location == textField.text?.length {
formattedString = formattedString?.appending(".")
}
textField.text = formattedString
} else {
textField.text = nil
}
}
return false
}
For Swift 3. Input currency format on a text field (from right to left)
#IBOutlet weak var textfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textfield.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged)
// Do any additional setup after loading the view.
}
#objc func myTextFieldDidChange(_ textField: UITextField) {
if let amountString = textField.text?.currencyInputFormatting() {
textField.text = amountString
}
}
}
extension String {
// formatting text for currency textField
func currencyInputFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currencyAccounting
formatter.currencySymbol = "$"
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
Hope this is helpful...

While entering text in UITextField placeholder should disappear one letter at at time

I have created a UITextfield where i want to add 4 digit password, but once I enter the first digit whole placeholder disappear. how can I keep next three placeholder letters in UITextfield while entering next password letters.
here is my screenshot:
I wanted to try SeanLintern88's solution because it sounded like a little challange. And it is in the case where the text field should have spaces between the underscore.
textField.text = "_ _ _ _"
This is the solution I came with and while it was fun to write, this is something I do not recommend using in real projects. Better try the 4 separate text fields approach :)
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return false }
var location = range.location
//is deleting
if string == "" {
guard let indexToReplace = text.index(text.startIndex, offsetBy: location, limitedBy: text.endIndex) else {
return false
}
let isCharDeleted = location % 2 == 0
//place " " or "_" depending on the position that was deleted
let stringToReplaceWith = isCharDeleted ? "_" : " "
let charachter = stringToReplaceWith[stringToReplaceWith.startIndex]
textField.text?.remove(at: indexToReplace)
textField.text?.insert(charachter, at: indexToReplace)
var newCursorPositionOffset = location
//deletetion occured on space " "
if !isCharDeleted {
guard let previousIndex = text.index(text.startIndex, offsetBy: location-1, limitedBy: text.endIndex) else {
return false
}
//delete the previous charachter
textField.text?.remove(at: previousIndex)
let dash = "_"
let char = dash[dash.startIndex]
textField.text?.insert(char, at: previousIndex)
//correct cursor position
newCursorPositionOffset -= 1
}
//move cursor position
let newPosition = textField.position(from: textField.beginningOfDocument, offset: newCursorPositionOffset)
textField.selectedTextRange = textField.textRange(from: newPosition!, to: newPosition!)
return false
}
//is typing
if range.location + 1 <= text.characters.count,
let end = text.index(text.startIndex, offsetBy: location+1, limitedBy: text.endIndex),
let start = text.index(text.startIndex, offsetBy: location, limitedBy: text.endIndex) {
textField.text = textField.text?.replacingOccurrences(of: "_", with: string, options: .caseInsensitive, range: Range(uncheckedBounds: (lower: start, upper: end)))
//correct the cursor position if placed on " " index
if range.location % 2 != 0 {
location -= 1
}
}
//skip " " and move cursor to the next "_"
if location+2 < text.characters.count {
let newPosition = textField.position(from: textField.beginningOfDocument, offset: location+2)
textField.selectedTextRange = textField.textRange(from: newPosition!, to: newPosition!)
}
return false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let newPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}
}
PS: Probably it can be made shorter with better choosing of functions for string operations, but still a pretty .. unfriendly solution.
Conclusion: DON'T DO THIS AT HOME :D
Instead of using placeHolder, just override the shouldChangeCharactersInRange method and append the characters to the string until the string is 4 characters long, you can also use attributed string if you want the _ to look different to the dots.
Swift 4
This is a modified version of #Denislava Shentova's answer that I believe simplifies into less lines of code, fixes issues, and makes the code more readable.
Not Fully Tested
import UIKit
class YourClass: UIViewController {
//It is also a good idea to deny users the ability to paste into this textField.
//set up textField
let textField : UITextField = {
let textField = UITextField()
// These are 'long dashes' you can replace them with whatever you would like.
// These look best IMO.
textField.text = "——————" //No spaces needed!
textField.textColor = .black
textField.textAlignment = .center
textField.tintColor = .clear //this will hide the cursor.
return textField
}()
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
//This sets the spacing or 'Kern' of the textfield. Adjust the value: 10.0 and the fontSize to get the desired output.
textField.defaultTextAttributes.updateValue(10.0, forKey: NSAttributedStringKey.kern.rawValue)
}
}
extension YourClass : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//get the current text of the textField.
guard let text = textField.text else { return false }
//handle backspace event.
if string == "" {
guard let indexToReplace = text.index(text.startIndex, offsetBy: range.location, limitedBy: text.endIndex) else { return false }
textField.text?.remove(at: indexToReplace)
textField.text?.insert("—", at: indexToReplace)
//adjust cursor position
if let newPostion = textField.position(from: textField.beginningOfDocument, offset: range.location) {
textField.selectedTextRange = textField.textRange(from: newPostion, to: newPostion)
return false
}
}
//handle character entered event.
if range.location + 1 <= text.count,
let end = text.index(text.startIndex, offsetBy: range.location + 1, limitedBy: text.endIndex),
let start = text.index(text.startIndex, offsetBy: range.location, limitedBy: text.endIndex) {
textField.text = textField.text?.replacingOccurrences(of: "—", with: string, options: .caseInsensitive, range: Range(uncheckedBounds: (lower: start, upper: end)))
}
//adjust cursor position.
if range.location + 1 < text.count {
if let newPosition = textField.position(from: textField.beginningOfDocument, offset: range.location + 1){
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}
}
return false
}
//make sure to start at the begining of the textField.
func textFieldDidBeginEditing(_ textField: UITextField) {
let newPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}
}

Swift NSAttributedString Trim

I want to get ride of the white spaces in front and at the end of my NSAttributedString(Trimming it). I can't simply convert it to string and do trimming because there are images(attachments) in it.
How can i do it?
Create extension of NSAttributedString as below.
extension NSAttributedString {
public func attributedStringByTrimmingCharacterSet(charSet: CharacterSet) -> NSAttributedString {
let modifiedString = NSMutableAttributedString(attributedString: self)
modifiedString.trimCharactersInSet(charSet: charSet)
return NSAttributedString(attributedString: modifiedString)
}
}
extension NSMutableAttributedString {
public func trimCharactersInSet(charSet: CharacterSet) {
var range = (string as NSString).rangeOfCharacter(from: charSet as CharacterSet)
// Trim leading characters from character set.
while range.length != 0 && range.location == 0 {
replaceCharacters(in: range, with: "")
range = (string as NSString).rangeOfCharacter(from: charSet)
}
// Trim trailing characters from character set.
range = (string as NSString).rangeOfCharacter(from: charSet, options: .backwards)
while range.length != 0 && NSMaxRange(range) == length {
replaceCharacters(in: range, with: "")
range = (string as NSString).rangeOfCharacter(from: charSet, options: .backwards)
}
}
}
and use in viewController where you want to use. like this
let attstring = NSAttributedString(string: "this is test message. Please wait. ")
let result = attstring.attributedStringByTrimmingCharacterSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
This works even with emoji in the text
extension NSAttributedString {
/** Will Trim space and new line from start and end of the text */
public func trimWhiteSpace() -> NSAttributedString {
let invertedSet = CharacterSet.whitespacesAndNewlines.inverted
let startRange = string.utf16.description.rangeOfCharacter(from: invertedSet)
let endRange = string.utf16.description.rangeOfCharacter(from: invertedSet, options: .backwards)
guard let startLocation = startRange?.upperBound, let endLocation = endRange?.lowerBound else {
return NSAttributedString(string: string)
}
let location = string.utf16.distance(from: string.startIndex, to: startLocation) - 1
let length = string.utf16.distance(from: startLocation, to: endLocation) + 2
let range = NSRange(location: location, length: length)
return attributedSubstring(from: range)
}
}
USAGE
let attributeString = NSAttributedString(string: "\n\n\n Hi 👋 👩‍👩‍👧👩‍👩‍👦‍👦👩‍👩‍👧‍👧👨‍👨‍👦👩‍👦👨‍👨‍👧‍👧👨‍👨‍👦‍👦👨‍👨‍👧‍👦👩‍👧‍👦👩‍👦‍👦👩‍👧‍👧👨‍👦 buddy. ")
let result = attributeString.trimWhiteSpace().string // Hi 👋 👩‍👩‍👧👩‍👩‍👦‍👦👩‍👩‍👧‍👧👨‍👨‍👦👩‍👦👨‍👨‍👧‍👧👨‍👨‍👦‍👦👨‍👨‍👧‍👦👩‍👧‍👦👩‍👦‍👦👩‍👧‍👧👨‍👦 buddy.
Swift 4 and above
extension NSMutableAttributedString {
func trimmedAttributedString() -> NSAttributedString {
let invertedSet = CharacterSet.whitespacesAndNewlines.inverted
let startRange = string.rangeOfCharacter(from: invertedSet)
let endRange = string.rangeOfCharacter(from: invertedSet, options: .backwards)
guard let startLocation = startRange?.upperBound, let endLocation = endRange?.lowerBound else {
return NSAttributedString(string: string)
}
let location = string.distance(from: string.startIndex, to: startLocation) - 1
let length = string.distance(from: startLocation, to: endLocation) + 2
let range = NSRange(location: location, length: length)
return attributedSubstring(from: range)
}
}
use:
let string = "This is string with some space in the end. "
let attributedText = NSMutableAttributedString(string: string).trimmedAttributedString()
It turns out that Unicode strings are hard hahaha! The other solutions posted here are a great starting point, but they crashed for me when using non-latin strings.
Whenever using indexes or ranges in Swift Strings, we need to use String.Index instead of plain Int. Creating an NSRange from a Range<String.Index> has to be done with NSRange(swiftRange, in: String).
That being said, this code builds on the other answers, but makes it unicode-proof:
public extension NSMutableAttributedString {
/// Trims new lines and whitespaces off the beginning and the end of attributed strings
func trimmedAttributedString() -> NSAttributedString {
let invertedSet = CharacterSet.whitespacesAndNewlines.inverted
let startRange = string.rangeOfCharacter(from: invertedSet)
let endRange = string.rangeOfCharacter(from: invertedSet, options: .backwards)
guard let startLocation = startRange?.lowerBound, let endLocation = endRange?.lowerBound else {
return NSAttributedString(string: string)
}
let trimmedRange = startLocation...endLocation
return attributedSubstring(from: NSRange(trimmedRange, in: string))
}
}
I made a swift 3 implementation, just in case anyone is interested:
/**
Trim an attributed string. Can for example be used to remove all leading and trailing spaces and line breaks.
*/
public func attributedStringByTrimmingCharactersInSet(set: CharacterSet) -> NSAttributedString {
let invertedSet = set.inverted
let rangeFromStart = string.rangeOfCharacter(from: invertedSet)
let rangeFromEnd = string.rangeOfCharacter(from: invertedSet, options: .backwards)
if let startLocation = rangeFromStart?.upperBound, let endLocation = rangeFromEnd?.lowerBound {
let location = string.distance(from: string.startIndex, to: startLocation) - 1
let length = string.distance(from: startLocation, to: endLocation) + 2
let newRange = NSRange(location: location, length: length)
return self.attributedSubstring(from: newRange)
} else {
return NSAttributedString()
}
}
Swift 3.2 Version:
extension NSAttributedString {
public func trimmingCharacters(in characterSet: CharacterSet) -> NSAttributedString {
let modifiedString = NSMutableAttributedString(attributedString: self)
modifiedString.trimCharacters(in: characterSet)
return NSAttributedString(attributedString: modifiedString)
}
}
extension NSMutableAttributedString {
public func trimCharacters(in characterSet: CharacterSet) {
var range = (string as NSString).rangeOfCharacter(from: characterSet)
// Trim leading characters from character set.
while range.length != 0 && range.location == 0 {
replaceCharacters(in: range, with: "")
range = (string as NSString).rangeOfCharacter(from: characterSet)
}
// Trim trailing characters from character set.
range = (string as NSString).rangeOfCharacter(from: characterSet, options: .backwards)
while range.length != 0 && NSMaxRange(range) == length {
replaceCharacters(in: range, with: "")
range = (string as NSString).rangeOfCharacter(from: characterSet, options: .backwards)
}
}
}
Following code will work for your requirement.
var attString: NSAttributedString = NSAttributedString(string: " this is att string")
let trimmedString = attString.string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Resources