set nslocale for number part of nsstring - ios

Is there any way to set locale on number part of string ?
like if nsstring is like this : "0.510.220" it shows this inside
uilabel view : "۰.۵۱۰.۲۲۰"
i know i can change the nslocale with this if number are valid :
NSDecimalNumber *someNumber = [NSDecimalNumber decimalNumberWithString:#"123"];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSLocale *gbLocale = [[[NSLocale alloc] initWithLocaleIdentifier:#"ar"] autorelease];
[formatter setLocale:gbLocale];
but how can i make that happen on full nsstring text? like number inside
string.also im want to make this happen on +7.0 sdk.

No, because what you want is not something that a locale does. "۰.۵۱۰.۲۲۰" is not "0.510.220" in a different locale, it's just simply a different string.
Strings don't have locales. They consist of characters. A string with the characters "0.510.220" has those characters, not others. The Arabic digits are different characters and so you'd need a string with different content.
An NSNumberFormatter is not applying a locale to a string. It's applying a locale to the conversion from a number to a string. That's completely different from what you seem to want.
You could try to parse your string to find a substring that appears to be a number, convert that substring to an actual number using one NSNumberFormatter in one locale, convert the resulting number back to a string using a second NSNumberFormatter in a different locale, and construct a new string by replacing the original substring with the new string.

Related

NSDateComponentsFormatter NSString to NSTimeInterval

I hope I didn't miss anything but from reading the documentation I get:
NSDateComponentsFormatter provides a method - (NSString * nullable)stringFromTimeInterval:(NSTimeInterval)ti which can be used to convert an NSTimeInterval into an NSString.
However I couldn't find any method that that converts the resulting string back into an NSTimeInterval.
Is their anything like an equivalent to NSDateFormatter - (NSDate *)dateFromString:(NSString *)string ?
Thanks in advance!
NSTimeInterval is simply a double value, so just get the doubleValue of the string.
NSTimeInterval ti = [yourString doubleValue];
EDIT: Per your comments, you are correct- I was making an assumption that the value returned by stringFromTimeInterval: was an unformatted double value. Based off some quick observations, there does not seem to be a simple way to convert the string back to a double value, regardless of the unitsStyle used in the NSDateComponentsFormatter, as none of the styles provide an easily-parseable format. I assume you would need to write your own method to search through the resulting string for ranges of substrings and do the math yourself.

Displaying two different types of variables in one label string

I am trying to make a CCLabelTTF display a string and an integer together. Like this:
Your score is 0.
I've tried a few things but I usually get the warning Data argument not used by format string, and the label doesn't output the correct statements.
I am just trying to figure out the format in which to put these in and searching Google hasn't provided much, as I'm not really sure what exactly to search.
I've tried
label.string = (#"%#", #"hi", #"%d", investmentsPurchased);
but obviously that isn't correct. How would I do this?
Thanks.
(I assume this is ObjC and not Swift.) Try something like this:
label.string = [NSString stringWithFormat:#"hi %d", investmentsPurchased];
You use a single format string, which contains static text and replacement tokens (like %d) for any replacement variables. Then follows the list of values to substitute in. You can use multiple variables like:
label.string = [NSString stringWithFormat:#"number %d and a string %#", someInteger, someString];
use NSString newString = [NSString stringWithFormat:#"hello %#", investmentsPurchased];
in short: use stringWithFormat

Multi-line string formatting issue in UILabel

I want my label to read like this:
Name of Activity
nn%
Instead, here's what appears:
%#
%f%
In addition, I'm getting this warning: Expression result unused
Here's the code I'm trying:
firstLabel.text = #"%#\n%#%",[self.thisSpec activityOfInterest],focusActivityPercent;
[self.thisSpec activityOfInterest] returns a string containing the name of an activity, and focusActivityPercent is a double.
This is the first time I've tried a multiline label.
Any suggestions?
Thanks
You can't specify string formatting on a string literal on its own like that. In fact, the code you've shown should be producing a syntax error. You have to use NSString's stringWithFormat: class method:
firstLabel.text = [NSString stringWithFormat:#"%#\n%#%",[self.thisSpec activityOfInterest],focusActivityPercent];

Voice over doesn't read phone number properly

I have phone number in below format
1-1xx-2xx-9565
Currently VO read it as "One (pause) One x x (pause) two x x (pause) minus nine thousand five hundred sixty five".
VO should read it as "One (pause) One x x (pause) two x x (pause) nine five six five".
What could be the problem? Is this wrong phone format?
Let's break down what is happening. VoiceOver doesn't know that the text you are presenting is a phone number and treats it like a sentence of text. In that text it tries to find distinct components and read them appropriately. For example, the text "buy 60 cantaloupes" has 3 components, "buy", "60", and "cantaloupes". The first is text and is read as text, the second is purely numerical and is best read out as "sixty", and the third is read as text.
Applying the same logic to your phone number.
(I'm not talking about actual implementation, just reasoning.)
If you read 1-1xx-2xx-9565 from the left to the right then the first distinct component is "1" which in it self is numerical and is read as "1". If the phone number would have started with "12-1xx" then the first component would have been read as "twelve" because its purely numerical.
The next component is "1xx" or "-1xx" depending on how you look at it. In either case it is a combination of numbers and letters, e.g. it is not purely numerical and is thus read out as text. If you include the "-" in that component is interpreted as a hyphen which isn't read out. That is why the the "-" is never read out for that component. The next component ("-2xx") is treated in the same way.
The final component is "-9565" which turns out to be a valid number. As seen in the cantaloupe sentence, VoiceOver reads this as a number in which case the "-" is no longer interpreted as a hyphen but as a "minus sign".
Getting VoiceOver to read your own text
On any label, view or other element in your application that is used with Voice Over, you can supply your own "accessibility label" when you know more about how you want the text to be read. This is done by simply assigning your own string to the accessibilityLabel property.
Now, you can create a suitable string in many different ways, a very simple one in your case would be to just add spaces everywhere so that each number is read individually. However, it seems a bit fragile to me, so I went ahead and used a number formatter to translate the individual numbers to their textual representations.
NSString *phoneNumber = #"1-1xx-2xx-9565";
// we want to know if a character is a number or not
NSCharacterSet *numberCharacters = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
// we use this formatter to spell out individual numbers
NSNumberFormatter *spellOutSingleNumber = [NSNumberFormatter new];
spellOutSingleNumber.numberStyle = NSNumberFormatterSpellOutStyle;
NSMutableArray *spelledOutComonents = [NSMutableArray array];
// loop over the phone number add add the accessible variants to the array
[phoneNumber enumerateSubstringsInRange:NSMakeRange(0, phoneNumber.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
// check if it's a number
if ([substring rangeOfCharacterFromSet:numberCharacters].location != NSNotFound) {
// is a number
NSNumber *number = #([substring integerValue]);
[spelledOutComonents addObject:[spellOutSingleNumber stringFromNumber:number]];
} else {
// is not a number
[spelledOutComonents addObject:substring];
}
}];
// finally separate the components with spaces (so that the string doesn't become "ninefivesixfive".
NSString *yourAccessiblePhoneNumber = [spelledOutComonents componentsJoinedByString:#" "];
The result when I ran this was
one - one x x - two x x - nine five six five
If you need to do other modifications to your phone numbers to get them to read appropriately then you can do that. I suspect that you will use this is more than one place in your app so creating a custom NSFormatter might be a good idea.
Edit
On iOS 7 you can also use the UIAccessibilitySpeechAttributePunctuation attribute on an attributes string to change how it is pronounced.
Speech Attributes for Attributed Strings
Attributes that you can apply to text in an attributed string to modify how that text is pronounced.
UIAccessibilitySpeechAttributePunctuation
The value of this key is an NSNumber object that you should interpret as a Boolean value. When the value is YES, all punctuation in the text is spoken. You might use this for code or other text where the punctuation is relevant.
Available in iOS 7.0 and later.
Declared in UIAccessibilityConstants.h.
As of iOS 13 you can use a - NSAttributedString.Key.accessibilitySpeechSpellOut as a accessibilityAttributedLabel to make VoiceOver read each letter of the provided string (or a range of string).
So for example:
yourView.accessibilityAttributedLabel = NSAttributedString(string: yourText, attributes: [.accessibilitySpeechSpellOut: true])
If you want to spell all characters individually, a simple solution is to separate the characters by a comma ",".
You can use a String extension to convert the string:
extension String
{
/// Returns string suitable for accessibility (voice over). All characters will be spelled individually.
func stringForSpelling() -> String
{
return stringBySeparatingCharactersWithString(",")
}
/// Inserts a separator between all characters
func stringBySeparatingCharactersWithString(separator: String) -> String
{
var s = ""
// Separate all characters
let chars = self.characters.map({ String($0) })
// Append all characters one by one
for char in chars {
// If there is already a character, append separator before appending next character
if s.characters.count > 0 {
s += separator
}
// Append next character
s += char
}
return s
}
}
And then use it in the code like this:
myLabel.accessibilityLabel = myString.stringForSpelling()
Just Add a comma to each digit of the last number and after the last digit as well,. this will make sure voice over reads the last number as same as previous numbers.
example your number :- 1-1xx-2xx-9565
accessibility label :- 1-1xx-2xx-9,5,6,5,
Here is the code in Swift
public func retrieveAccessiblePhoneNumber(phoneNumber: String) -> String {
// We want to know if a character is a number or not
let characterSet = NSCharacterSet(charactersInString: "0123456789")
// We use this formatter to spell out individual numbers
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .SpellOutStyle
var spelledOutComponents = [String]()
let range = Range<String.Index>(start: phoneNumber.startIndex, end: phoneNumber.endIndex)
// Loop over the phone number add add the accessible variants to the array
phoneNumber.enumerateSubstringsInRange(range,
options: NSStringEnumerationOptions.ByComposedCharacterSequences) { (substring, substringRange, enclosingRange, stop) -> () in
// Check if it's a number
if let substr = substring where substr.rangeOfCharacterFromSet(characterSet) != nil {
if let number = Int(substr) {
// Is a number
let nsNumber = NSNumber(integer: number)
spelledOutComponents.append(numberFormatter.stringFromNumber(nsNumber)!)
}
} else {
// Is not a number
spelledOutComponents.append(substring!)
}
}
// Finally separate the components with spaces (so that the string doesn't become "ninefivesixfive".
return spelledOutComponents.joinWithSeparator(" ")
}

Decimal point in calculations as . or ,

If I use decimal pad for input of numbers the decimal changes depending of country and region format.
May be as a point "." or as a comma ","
And I do not have control over at which device the app is used.
If the region format uses a comma the calculation gets wrong. Putting in 5,6 is the the same as putting in only 5 some times and as 56 same times.
And that is even if I programmatically allow both . and , as input in a TextField.
How do I come around this without using the numbers an punctation pad and probably also have to give instructions to avoid input with comma ","
It is only input for numbers and decimal I need and the decimal pad is so much nicer.
You shoudld use a NSNumberFormatter for this, as this can be set to handle different locales.
Create a formatter:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[NSLocale currentLocale]];
Use it:
NSNumber *number = [numberFormatter numberFromString: string]; //string is the textfield.text
if the device's locale is set to a locale, where the decimal separator in a ,, the Number Keypad will use is and the formatter as-well. On those the grouping separator will be .
For the other locales it will be vice-versa.
NSNumberFormatter is very sophisticated, you should read its section in Data Formatter Guide, too. It also knows a lot of currency handling (displaying, not conversion), if your app does handle such.
You can use also the class method of NSNumberFormatter
NSString* formattedString = [NSNumberFormatter
localizedStringFromNumber:number
numberStyle:NSNumberFormatterCurrencyStyle];
Identify is local country uses comma for decimal point
var isUsesCommaForDecimal : Bool {
let nf = NumberFormatter()
nf.locale = Locale.current
let numberLocalized = nf.number(from: "23,34")
if numberLocalized != nil {
return true
} else {
return false
}
}
One way could be to check if the textField contains a ",".
If it contains, replace it with "." and do all arithmetic operations.
As anyways you will be reading all textFields and textViews as NSString object, you can manipulate the input value and transform it according to your need.
Also while showing the result replace "." with "," so that user feel comfortable according to there regional formats.

Resources