I want to format my UITextField with having a $ on the left when I enter an amount.
So far what my code does is when I enter let says $5.65 this is how it's entered: $0.05 -> $0.56 -> $5.65
I want it so that it's not right to left but left to right so something like this: $5 -> $5. -> $5.6 -> $5.65
But I want to restrict it to only two decimals place, the dollar sign is on the left, and you can not type any other characters (e.g: !,#,#,$,%,^, A-Z')
This is what I have currently:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text: NSString = (textField.text ?? "") as NSString
let finalString = text.replacingCharacters(in: range, with: string)
// 'currency' is a String extension that doews all the number styling
amuTextField.text = finalString.currency
// returning 'false' so that textfield will not be updated here, instead from styling extension
return false
}
func currencyInputFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currencyAccounting
formatter.currencySymbol = "$"
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))
return formatter.string(from: number)!
}
You could use this to limit the decimal places after the .:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldText = textField.text, let r = Range(range, in: oldText) else {
return true
}
let newText = oldText.replacingCharacters(in: r, with: string)
let isNumeric = newText.isEmpty || (Double(newText) != nil)
let numberOfDots = newText.components(separatedBy: ".").count - 1
let numberOfDecimalDigits: Int
if let dotIndex = newText.firstIndex(of: ".") {
numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
} else {
numberOfDecimalDigits = 0
}
return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2
}
I am doing validation on my UITextField. It should accept only number and . character. Basically user can enter any decimal number like :
1.0
1.23
1.45
12.47
Also I have to add % sign while editing in textfield like below:
When User enter 1, textfield should update 1 %
When User enter 1.2, textfield should update 1.2 %
When User enter 18.345, textfield should update 18.345 %
I am using below Code to achieve this:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
if string.characters.count == 0 {
return true
}
do {
if textField == self.questionTextFeild {
let nString = textField.text as NSString?
let newString = nString?.replacingCharacters(in: range, with: string)
let expression = "^([0-9]+)?(\\.([0-9]{1,8})?)?$"
let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive)
let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.characters.count)!))
//textField.text = textField.text!
if numberOfMatches == 0 {
return false
}
}
}
catch let error {
}
return true
}
Using this I can able to enter numbers and dot character. My problem is how can I add % sign? Please suggest me.
Please find the updated code for adding percentage to last of the number while typing
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
if string.count == 0 {
return true
}
do {
if textField == textField {
let nString = textField.text as NSString?
let newString = nString?.replacingCharacters(in: range, with: string)
if var textString = textField.text {
let unitString = " %"
if textString.contains(unitString) {
textString = textString.replacingOccurrences(of: unitString, with: "")
textString += string + unitString
textField.text = textString
} else {
textField.text = string + unitString
}
}
let expression = "^([0-9]+)?(\\.([0-9]{1,8})?)?$"
let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive)
let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.count)!))
//textField.text = textField.text!
if numberOfMatches == 0 {
return false
}
}
}
catch let error {
print(error.localizedDescription)
}
return true
}
I have the following function to find and highlight hashtags or mentions (# or #) in a UILabel:
class func addLinkAttribute(pattern: String,
toText text: String,
withAttributeName attributeName : String,
toAttributedString attributedString :NSMutableAttributedString,
withLinkAttributes linkAttributes: [NSObject : AnyObject]) {
var error: NSError?
if let regex = NSRegularExpression(pattern: pattern, options:.CaseInsensitive, error: &error) {
regex.enumerateMatchesInString(text, options: .allZeros, range: NSMakeRange(0, count(text))) { result, flags, stop in
let range = result.range
let start = advance(text.startIndex, range.location)
let end = advance(start, range.length)
let foundText = text.substringWithRange(Range<String.Index>(start: start,end: end))
var linkAttributesWithName = linkAttributes
linkAttributesWithName[attributeName] = foundText
attributedString.addAttributes(linkAttributesWithName, range: range)
}
}
}
If I pass a hashtag (#)(\\w+) or mention (#)(\\w+) pattern the code works perfectly but if the text contains an Emoji the range is offset by the number of emojis preceding it:
I know Swift treats strings differently to Objective-C, since count(string) and count(string.utf16) give me different results, but I am stumped as to how to account for this when using a regular expression.
I could just check the difference between the 2 counts and offset the range, but this seems wrong and hacky to me. There must be another way.
Similarly as in Swift extract regex matches, a possible solution is to convert the given Swift String
to an NSString and apply the NSRanges returned by
enumerateMatchesInString() to that NSString:
class func addLinkAttribute(pattern: String,
toText text: String,
withAttributeName attributeName : String,
toAttributedString attributedString :NSMutableAttributedString,
withLinkAttributes linkAttributes: [NSObject : AnyObject]) {
let nsText = text as NSString
var error: NSError?
if let regex = NSRegularExpression(pattern: pattern, options:.CaseInsensitive, error: &error) {
regex.enumerateMatchesInString(text, options: .allZeros, range: NSMakeRange(0, nsText.length)) {
result, _, _ in
let range = result.range
let foundText = nsText.substringWithRange(range)
var linkAttributesWithName = linkAttributes
linkAttributesWithName[attributeName] = foundText
attributedString.addAttributes(linkAttributesWithName, range: range)
}
}
}
(Alternative solution.) It is possible to convert an NSRange to Range<String.Index> without intermediate conversion to an NSString.
With
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let utf16start = self.utf16.startIndex
if let from = String.Index(self.utf16.startIndex + nsRange.location, within: self),
let to = String.Index(self.utf16.startIndex + nsRange.location + nsRange.length, within: self) {
return from ..< to
}
return nil
}
}
from https://stackoverflow.com/a/30404532/1187415, your code can be
written as
class func addLinkAttribute(pattern: String,
toText text: String,
withAttributeName attributeName : String,
toAttributedString attributedString :NSMutableAttributedString,
withLinkAttributes linkAttributes: [NSObject : AnyObject]) {
var error: NSError?
if let regex = NSRegularExpression(pattern: pattern, options:.CaseInsensitive, error: &error) {
regex.enumerateMatchesInString(text, options: .allZeros, range: NSMakeRange(0, count(text.utf16))) {
result, _, _ in
let nsRange = result.range
if let strRange = text.rangeFromNSRange(nsRange) {
let foundText = text.substringWithRange(strRange)
var linkAttributesWithName = linkAttributes
linkAttributesWithName[attributeName] = foundText
attributedString.addAttributes(linkAttributesWithName, range: nsRange)
}
}
}
}
and that should also work correctly for all kinds of extended grapheme
clusters (Emojis, Regional Indicators etc...)
Problem: NSAttributedString takes an NSRange while I'm using a Swift String that uses Range
let text = "Long paragraph saying something goes here!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
Produces the following error:
error: 'Range' is not convertible to 'NSRange'
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
Swift String ranges and NSString ranges are not "compatible".
For example, an emoji like π counts as one Swift character, but as two NSString
characters (a so-called UTF-16 surrogate pair).
Therefore your suggested solution will produce unexpected results if the string
contains such characters. Example:
let text = "πππLong paragraph saying!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
let start = distance(text.startIndex, substringRange.startIndex)
let length = distance(substringRange.startIndex, substringRange.endIndex)
let range = NSMakeRange(start, length)
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
}
})
println(attributedString)
Output:
πππLong paragra{
}ph say{
NSColor = "NSCalibratedRGBColorSpace 1 0 0 1";
}ing!{
}
As you see, "ph say" has been marked with the attribute, not "saying".
Since NS(Mutable)AttributedString ultimately requires an NSString and an NSRange, it is actually
better to convert the given string to NSString first. Then the substringRange
is an NSRange and you don't have to convert the ranges anymore:
let text = "πππLong paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: nsText)
nsText.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
println(attributedString)
Output:
πππLong paragraph {
}saying{
NSColor = "NSCalibratedRGBColorSpace 1 0 0 1";
}!{
}
Update for Swift 2:
let text = "πππLong paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: text)
nsText.enumerateSubstringsInRange(textRange, options: .ByWords, usingBlock: {
(substring, substringRange, _, _) in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
print(attributedString)
Update for Swift 3:
let text = "πππLong paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: text)
nsText.enumerateSubstrings(in: textRange, options: .byWords, using: {
(substring, substringRange, _, _) in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.red, range: substringRange)
}
})
print(attributedString)
Update for Swift 4:
As of Swift 4 (Xcode 9), the Swift standard library
provides method to convert between Range<String.Index> and NSRange.
Converting to NSString is no longer necessary:
let text = "πππLong paragraph saying!"
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: .byWords) {
(substring, substringRange, _, _) in
if substring == "saying" {
attributedString.addAttribute(.foregroundColor, value: NSColor.red,
range: NSRange(substringRange, in: text))
}
}
print(attributedString)
Here substringRange is a Range<String.Index>, and that is converted to the
corresponding NSRange with
NSRange(substringRange, in: text)
For cases like the one you described, I found this to work. It's relatively short and sweet:
let attributedString = NSMutableAttributedString(string: "follow the yellow brick road") //can essentially come from a textField.text as well (will need to unwrap though)
let text = "follow the yellow brick road"
let str = NSString(string: text)
let theRange = str.rangeOfString("yellow")
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: theRange)
The answers are fine, but with Swift 4 you could simplify your code a bit:
let text = "Test string"
let substring = "string"
let substringRange = text.range(of: substring)!
let nsRange = NSRange(substringRange, in: text)
Be cautious, as the result of range function has to be unwrapped.
Possible Solution
Swift provides distance() which measures the distance between start and end that can be used to create an NSRange:
let text = "Long paragraph saying something goes here!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
let start = distance(text.startIndex, substringRange.startIndex)
let length = distance(substringRange.startIndex, substringRange.endIndex)
let range = NSMakeRange(start, length)
// println("word: \(substring) - \(d1) to \(d2)")
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
}
})
For me this works perfectly:
let font = UIFont.systemFont(ofSize: 12, weight: .medium)
let text = "text"
let attString = NSMutableAttributedString(string: "exemple text :)")
attString.addAttributes([.font: font], range:(attString.string as NSString).range(of: text))
label.attributedText = attString
Swift 4:
Sure, I know that Swift 4 has an extension for NSRange already
public init<R, S>(_ region: R, in target: S) where R : RangeExpression,
S : StringProtocol,
R.Bound == String.Index, S.Index == String.Index
I know in most cases this init is enough. See its usage:
let string = "Many animals here: πΆπ¦π± !!!"
if let range = string.range(of: "πΆπ¦π±"){
print((string as NSString).substring(with: NSRange(range, in: string))) // "πΆπ¦π±"
}
But conversion can be done directly from Range< String.Index > to NSRange without Swift's String instance.
Instead of generic init usage which requires from you the target parameter as String and
if you don't have target string at hand you can create conversion directly
extension NSRange {
public init(_ range:Range<String.Index>) {
self.init(location: range.lowerBound.encodedOffset,
length: range.upperBound.encodedOffset -
range.lowerBound.encodedOffset) }
}
or you can create the specialized extension for Range itself
extension Range where Bound == String.Index {
var nsRange:NSRange {
return NSRange(location: self.lowerBound.encodedOffset,
length: self.upperBound.encodedOffset -
self.lowerBound.encodedOffset)
}
}
Usage:
let string = "Many animals here: πΆπ¦π± !!!"
if let range = string.range(of: "πΆπ¦π±"){
print((string as NSString).substring(with: NSRange(range))) // "πΆπ¦π±"
}
or
if let nsrange = string.range(of: "πΆπ¦π±")?.nsRange{
print((string as NSString).substring(with: nsrange)) // "πΆπ¦π±"
}
Swift 5:
Due to the migration of Swift strings to UTF-8 encoding by default, the usage of encodedOffset is considered as deprecated and Range cannot be converted to NSRange without an instance of String itself, because in order to calculate the offset we need the source string which is encoded in UTF-8 and it should be converted to UTF-16 before calculating offset. So best approach, for now, is to use generic init.
Swift 5 Solution
Converting Range into NSRange
As the 'encodedOffset' is deprecated, so now in order to convert String.Index to Int we need the reference of original string from which Range<String.Index> was derived.
A convenient detailed extension for NSRange could be as below:
extension NSRange {
public init(range: Range<String.Index>,
originalText: String) {
let range_LowerBound_INDEX = range.lowerBound
let range_UpperBound_INDEX = range.upperBound
let range_LowerBound_INT = range_LowerBound_INDEX.utf16Offset(in: originalText)
let range_UpperBound_INT = range_UpperBound_INDEX.utf16Offset(in: originalText)
let locationTemp = range_LowerBound_INT
let lengthTemp = range_UpperBound_INT - range_LowerBound_INT
self.init(location: locationTemp,
length: lengthTemp)
}
}
While the shorthand extension is as below
extension NSRange {
public init(range: Range<String.Index>,
originalText: String) {
self.init(location: range.lowerBound.utf16Offset(in: originalText),
length: range.upperBound.utf16Offset(in: originalText) - range.lowerBound.utf16Offset(in: originalText))
}
}
Now we can use any Range to convert it into NSRange as below, sharing my own requirement which led me to write above extensions
I was using below String extension for finding all the ranges of specific word from the String
extension String {
func ranges(of substring: String, options: CompareOptions = [], locale: Locale? = nil) -> [Range<Index>] {
var ranges: [Range<Index>] = []
while let range = range(of: substring, options: options, range: (ranges.last?.upperBound ?? self.startIndex)..<self.endIndex, locale: locale) {
ranges.append(range)
}
return ranges
}
}
My requirement was to change the colour of specific words in a String, so for that I wrote this extension which does the job
extension NSAttributedString {
static func colored(originalText:String,
wordToColor:String,
currentColor:UIColor,
differentColor:UIColor) -> NSAttributedString {
let attr = NSMutableAttributedString(string: originalText)
attr.beginEditing()
attr.addAttribute(NSAttributedString.Key.foregroundColor,
value: currentColor,
range: NSRange(location: 0, length: originalText.count))
// FOR COVERING ALL THE OCCURENCES
for eachRange in originalText.ranges(of: wordToColor) {
attr.addAttribute(NSAttributedString.Key.foregroundColor,
value: differentColor,
range: NSRange(range: eachRange, originalText: originalText))
}
attr.endEditing()
return attr
}
}
Finally I was using it from my main code as below
let text = "Collected".localized() + " + " + "Cancelled".localized() + " + " + "Pending".localized()
myLabel.attributedText = NSAttributedString.colored(originalText: text,
wordToColor: "+",
currentColor: UIColor.purple,
differentColor: UIColor.blue)
And the result is as below, having the colour of + sign changed as blue from the main text colour which is purple.
Hope this helps someone in need. Thanks!
Swift 4
I think, there are two ways.
1. NSRange(range, in: )
2. NSRange(location:, length: )
Sample code:
let attributedString = NSMutableAttributedString(string: "Sample Text 12345", attributes: [.font : UIFont.systemFont(ofSize: 15.0)])
// NSRange(range, in: )
if let range = attributedString.string.range(of: "Sample") {
attributedString.addAttribute(.foregroundColor, value: UIColor.orange, range: NSRange(range, in: attributedString.string))
}
// NSRange(location: , length: )
if let range = attributedString.string.range(of: "12345") {
attributedString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: range.lowerBound.encodedOffset, length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset))
}
Screen Shot:
Swift 3 Extension Variant that preserves existing attributes.
extension UILabel {
func setLineHeight(lineHeight: CGFloat) {
guard self.text != nil && self.attributedText != nil else { return }
var attributedString = NSMutableAttributedString()
if let attributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: attributedText)
} else if let text = self.text {
attributedString = NSMutableAttributedString(string: text)
}
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
style.alignment = self.textAlignment
let str = NSString(string: attributedString.string)
attributedString.addAttribute(NSParagraphStyleAttributeName,
value: style,
range: str.range(of: str as String))
self.attributedText = attributedString
}
}
func formatAttributedStringWithHighlights(text: String, highlightedSubString: String?, formattingAttributes: [String: AnyObject]) -> NSAttributedString {
let mutableString = NSMutableAttributedString(string: text)
let text = text as NSString // convert to NSString be we need NSRange
if let highlightedSubString = highlightedSubString {
let highlightedSubStringRange = text.rangeOfString(highlightedSubString) // find first occurence
if highlightedSubStringRange.length > 0 { // check for not found
mutableString.setAttributes(formattingAttributes, range: highlightedSubStringRange)
}
}
return mutableString
}
I love the Swift language, but using NSAttributedString with a Swift Range that is not compatible with NSRange has made my head hurt for too long. So to get around all that garbage I devised the following methods to return an NSMutableAttributedString with the highlighted words set with your color.
This does not work for emojis. Modify if you must.
extension String {
func getRanges(of string: String) -> [NSRange] {
var ranges:[NSRange] = []
if contains(string) {
let words = self.components(separatedBy: " ")
var position:Int = 0
for word in words {
if word.lowercased() == string.lowercased() {
let startIndex = position
let endIndex = word.characters.count
let range = NSMakeRange(startIndex, endIndex)
ranges.append(range)
}
position += (word.characters.count + 1) // +1 for space
}
}
return ranges
}
func highlight(_ words: [String], this color: UIColor) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: self)
for word in words {
let ranges = getRanges(of: word)
for range in ranges {
attributedString.addAttributes([NSForegroundColorAttributeName: color], range: range)
}
}
return attributedString
}
}
Usage:
// The strings you're interested in
let string = "The dog ran after the cat"
let words = ["the", "ran"]
// Highlight words and get back attributed string
let attributedString = string.highlight(words, this: .yellow)
// Set attributed string
label.attributedText = attributedString
My solution is a string extension that first gets the swift range then get's the distance from the start of the string to the start and end of the substring.
These values are then used to calculate the start and length of the substring. We can then apply these values to the NSMakeRange constructor.
This solution works with substrings that consist of multiple words, which a lot of the solutions here using enumerateSubstrings let me down on.
extension String {
func NSRange(of substring: String) -> NSRange? {
// Get the swift range
guard let range = range(of: substring) else { return nil }
// Get the distance to the start of the substring
let start = distance(from: startIndex, to: range.lowerBound) as Int
//Get the distance to the end of the substring
let end = distance(from: startIndex, to: range.upperBound) as Int
//length = endOfSubstring - startOfSubstring
//start = startOfSubstring
return NSMakeRange(start, end - start)
}
}
let text:String = "Hello Friend"
let searchRange:NSRange = NSRange(location:0,length: text.characters.count)
let range:Range`<Int`> = Range`<Int`>.init(start: searchRange.location, end: searchRange.length)