Detect Cut operation in textfield - Swift - ios

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.

Related

Formatting Currency - Swift

I am looking for a textfield currency formatter such that it fulfils the following criterias:
It should be formatted(comma separated) as I am typing
10 digits before decimal point and 2 digits after it, should be allowed
It should allow a regex for (2)
When we cut, cursor should remain at the same place
When we type in the middle of the currency, cursor should not shift to left.
It should support localization (Commas and Periods) in regex.
I have tried alot of solutions:
Using NSCharacterSet (This is the closest but regex fails here due to interchange of . and , during localization, also we have used .decimal type here to avoid the $ in textField)
class func checkTextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textBeforeEditing = textField.text else {
return true
}
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(".")
}
textField.text = formattedString
currentPosition = getCursorPositionForTextField(string: string, cursorPosition: currentPosition, formattedString: formattedString, textBeforeEditing: textBeforeEditing)
handleTextFieldCursor(cursorPosition: currentPosition, textField: textField)
return false
}
Using NumberFormatter but cursor shifts to end on every cut/paste
extension String {
func currencyInputFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
var amountWithPrefix = self
// remove from String: "$", ".", ","
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)!
}
}
I have spent almost a day or two finding a 100% workable solution but not able to resolve.
Any help will be appreciated
EDIT
I have come quite close to the solution with the help of the #denis_lor answer but still unable to achieve the interchange of comma with period. Here's my updated code, am I missing something? It works fine with english but not with spanish.
class func checkTextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textBeforeEditing = textField.text else {
return true
}
if ((string == "0" || string == "") && (textField.text! as NSString).range(of: "\(NSLocalizedString("core_decimal_separator_symbol", comment: ""))").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\(NSLocalizedString("core_decimal_separator_symbol", comment: ""))").inverted
let filtered = string.components(separatedBy: allowedCharacterSet)
let component = filtered.joined(separator: "")
let isNumeric = string.replacingOccurrences(of: NSLocalizedString("core_thousand_separator_symbol", comment: ""), 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: NSLocalizedString("core_thousand_separator_symbol", comment: ""), 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 == NSLocalizedString("core_decimal_separator_symbol", comment: "") && range.location == textField.text?.count {
formattedString = formattedString.appending(NSLocalizedString("core_decimal_separator_symbol", comment: ""))
}
textField.text = formattedString
currentPosition = getCursorPositionForTextField(string: string, cursorPosition: currentPosition, formattedString: formattedString, textBeforeEditing: textBeforeEditing)
handleTextFieldCursor(cursorPosition: currentPosition, textField: textField)
return false
}
Ok so it looks your concern here could be solved by making a first round implementation of your first solution, where you only need to think about localization of , and .. That is easy, you could implement it in many different ways, but the important part is you have your app for example localized in let's say two language that treats decimals and thousands with different symbols (let's assume as an example those languages are english and italian):
[en] language treats the separation of decimals with a , and thousands with a .
[it] language treats the separation of decimals with a . and thousands with a ,
A) What you could do is to create a Localizable.strings file and then localize your project in let's say english and italian as an example. To do it add the language here.
B) Then go to your Localizable.strings file and localize it for the languages you support (English and Italian as an example), like in this image that was done for German and English
You will end up with two Localizable.strings now, one for English and one for Italian:
Localizable.strings (English)
core_decimal_separator_symbol = ",";
core_thousand_separator_symbol = ".";
Localizable.strings (Italian)
core_decimal_separator_symbol = ".";
core_thousand_separator_symbol = ",";
C) And in your code, everywhere you need to address, for example, your decimal separator symbol, instead of writing it hard coded you could do something like:
removeDecimalSeparator = numberAsString.replacingOccurrences(of: NSLocalizedString("core_decimal_separator_symbol", comment: ""), with: "")
So whenever your app is localized to English for example this code will traslate into:
removeDecimalSeparator = numberAsString.replacingOccurrences(of: ",", with: "")
And when your app is localized to Italian for example this code will traslate into:
removeDecimalSeparator = numberAsString.replacingOccurrences(of: ".", with: "")
To conclude: consider these as example taking into account the Localizable.strings we have in this answer. Just to show you how you could manipulate some symbols in different ways for different languages by using Localization in your app.

Textfield Validation using CharacterSet

I have written below code to validate text input in textfield.
else if (textField == txtField_Password)
{
let charSet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$&*!")
let charLength = (txtField_Password.text!.count) + (string.count) - range.length
for i in 0..<string.count
{
let c = (string as NSString).character(at: i)
if (!((charSet as NSCharacterSet).characterIsMember(c)))
{
return false
}
}
return (charLength > 20) ? false : true
}
Can anyone help me to convert character(at:) and characterIsMember() part to its swift equivalent in the above code.
You can simplify the logic just by checking the range of the inverted character set. If the string contains only allowed characters the function returns nil.
else if textField == txtField_Password {
let charLength = txtField_Password.text!.utf8.count + string.utf8.count - range.length
let charSet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$&*!")
return string.rangeOfCharacter(from: charSet.inverted) == nil && charLength < 21
}
Note that there is a simpler way to implement what you want using a regular expression:
let currentText = (textField.text ?? "") as NSString
let newText = currentText.replacingCharacters(in: range, with: string)
let pattern = "^[a-zA-Z0-9#$&*!]{0,20}$"
return newText.range(of: pattern, options: .regularExpression) != nil
You could work with something along these lines. I appreciate this is a bit rough and ready but should work:
charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$&*!"
if txtField_Password.text!.count <= 20 {
for i in 0..<str.count
{
let c = Array(str)[i]
let cString = String(c)
if charSet.contains(cString) {
return false
}
}
} else {
return false
}
Use rangeOfCharacter:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let specialCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$&*!"
let characterSet = CharacterSet(charactersIn: specialCharacters)
guard let lengh = textfield.text else {return}
if lengh.count >= 20 {
// text exceeded 20 characters. Do something
}
if (string.rangeOfCharacter(from: characterSet) != nil) {
print("matched")
return true
} else {
print("not matched")
}
return true
}

How to replace string in particular range in iOS Swift?

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.

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...

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