Programmatically and automatically adding an integer into a UILabel? Possible? - ios

I've set up a simple if statement that says if the input length is equal to 3 make the next character a "-".
It works well, but I'd like the "-" to automatically be put there after I press my button for the 3rd time. So I press, "1", "2", then when I press the "3" it automatically puts a "-" directly afterwards. Currently the "-" only gets placed when I hit the button for the 4th time?
-(IBAction)buttonDigitPressed:(id)sender {
NSString *val = phoneNumberLabel.text;
int length = [val length];
} else {
NSString *tagValue = [NSString stringWithFormat:#"%d", [sender tag]];
phoneNumberLabel.text = [val stringByAppendingString: tagValue];
if (length == 3) {
phoneNumberLabel.text = [val stringByAppendingString:#"-"];
}
if (length == 7) {
phoneNumberLabel.text = [val stringByAppendingString:#"-"];
}
}
}
Any help would be appreciated, greatly! Thanks!

-(IBAction)buttonDigitPressed:(id)sender {
NSString *val = phoneNumberLabel.text;
NSString *newValue = #"";
NSString *dash = #"";
int length = [val length];
if ( ((length == 3) || (length == 7)) ) {
dash = #"-";
}
newValue = [NSString stringWithFormat:#"%#%#%d", val, dash, [sender tag]];
phoneNumberLabel.text = newValue;
}

Add the following code in buttonClicked method
if ([myLabel.text length] == 3)
{
myLabel.text = [val stringByAppendingString:#"-"];
}

Just add that code in the same method after you update the label with the integer.

Try this method,hope it will help you.
Keep UILabel object blank in xib.
- (IBAction)pressAction:(UIButton*)sender
{
if (lbl.text.length<=2) {
lbl.text=[lbl.text stringByAppendingFormat:#"%i",sender.tag];
}
if (lbl.text.length>=3){
lbl.text=[lbl.text stringByAppendingString:#"-"];
}
}

You can send the button the events. like [button sendActionsForControlEvents:UIControlEventTouchUpInside]
Or even perform selector after delay may do the trick for you.
both the cases you need not press a button
For the addition of "-" just check how many characters have been entered and when the third character has been entered add the "-".

Related

Prevent Users from Entering Multiple Decimals In Objective-C

I am making an only number input app (still) in which users press a button, I store a value into a string to display in a label.
Works great for the most part, except I cannot figure out how to prevent users from entering more than one decimal in a single string. .
I looked at this Stack overflow question, but trying to amend the code for my own just resulted in a whole bunch of errors. Does anyone have any advice?
- (void)numberBtn:(UIButton *)sender {
if (self.sales.text.length < 10) {
if(self.sales.text.length != 0){
NSString *lastChar = [self.sales.text substringFromIndex:[self.sales.text length] - 1];
if([lastChar isEqualToString:#"."] && [sender.titleLabel.text isEqualToString:#"."] && [sender.titleLabel.text stringByAppendingString:#"."]){
return;
}
if ([lastChar isEqualToString:#""] && [sender.titleLabel.text isEqualToString:#""]){
self.numbers = #"0.";
}
if ([self.sales.text rangeOfString:#"."].length > 0) {
NSArray *array = [self.sales.text componentsSeparatedByString:#"."];
if (array.count == 2) {
NSString *decimal = array.lastObject;
if (decimal.length > 2) {
return;
}
}
}
}
self.numbers = [NSString stringWithFormat:#"%#%#",self.numbers,sender.titleLabel.text];
self.sales.text = self.numbers;
}
}
Two steps...
Check to see if the button is a decimal .
if yes, see if the current label text already contains a .
If it does, return. If not, continue processing your button input:
- (void)numberBtn:(UIButton *)sender {
NSString *btnTitle = sender.currentTitle;
NSString *curText = self.sales.text;
if ([btnTitle isEqualToString:#"."]) {
if ([curText containsString:#"."]) {
NSLog(#"%# : Already has a decimal point!", curText);
return;
}
}
// whatever else you want to do with the input...
}

Delete Button Calculator *Help*

I have this code for my calculator that lets me delete one number at a time!
- (IBAction)deleteButton:(id)sender {
NSString *string = [Screen text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1];
if ([temp length] == 0) {
temp = #"0";
}
[Screen setText:temp];
}
It works, but whenever I enter another number, it resets back to the whole thing, so lets take this as an example.
I have the number 5678, (I deleted 678), So my new number is 5, (Now if I press another number), it goes back to 56781 ( 1 being the new number)
Heres my full code for my project! ---> http://txt.do/oduh
As seen in your code, you are using SelectNumber to store value everywhere, but in deleteButton method you are not storing new value in SelectNumber. So you need to set the new value in deleteButton.
- (IBAction)deleteButton:(id)sender {
NSString *string = [Screen text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1];
if ([temp length] == 0) {
temp = #"0";
}
SelectNumber = [temp intValue]; // set new value here
[Screen setText:temp];
}

How to display hyphen in uilabel?

How to display hyphen with UILabel like this, - A I origine - , Here I use the string appending method. I get this type of output - À l'origine de la guerre -. But I want display hyphen before the starting point of text and display hyphen after 10 charatcers.
I was searched but i can't get valied source. kindly give any suggestion if you know.
NSString *tempStr = #" - ";
tempStr = [tempStr stringByAppendingString:NSLocalizedString(#"OriginallyWar", #"")];
tempStr = [tempStr stringByAppendingString:#" -"];
[headingLabel setText:tempStr];
[headingLabel setFont:MRSEAVES_BOLD(17)];
Use NSMutableString and insert characters,
[yourString insertString:#"-" atIndex:10];
if you are using StoryBoard directly set it to the text property on Attribute inspector. Put 10 empty spaces after the end of character and the -.
You may try this code
NSString *inputString = #"OriginallyWarDFdfsdfdDFSDfdsfdsfDFdsfadsfawerdsaf";
NSMutableString *localizedInputString = [NSMutableString stringWithString:NSLocalizedString(inputString, #"")];
int numberOfCharacters = localizedInputString.length;
int numberOf10s = (numberOfCharacters/10 + 1);
int numberOfCharactersToBeInserted = 0;
for (int i = 1; i < numberOf10s; i++) {
int characterIndex = (i * 10) + numberOfCharactersToBeInserted;
if (i == (numberOf10s - 1) && numberOfCharacters % 10 == 0) {
[localizedInputString insertString:#" -" atIndex:characterIndex];
numberOfCharactersToBeInserted = 2 * i;
} else {
[localizedInputString insertString:#" - " atIndex:characterIndex];
numberOfCharactersToBeInserted = 3 * i;
}
}
if (numberOfCharacters == 0) {
[localizedInputString insertString:#"-" atIndex:0];
} else {
[localizedInputString insertString:#"- " atIndex:0];
}
NSLog(#"localizedInputString : %#", localizedInputString);
try using NSMutableString
NSString *tempStr = #" - ";
tempStr = [tempStr stringByAppendingString:NSLocalizedString(#"OriginallyWar", #"")];
NSMutableString *tempStrMutable=[[NSMutableString alloc]initWithString:tempStr];
[tempStrMutable insertString:#"-" atIndex:10];
[headingLabel setText:tempStrMutable];

How to merge 2 NSStrings with a formatter?

Merging these two strings:
#"###.##"
#"123"
Should output:
#"1.23"
I have developed a solution for this, but I'm looking for a simpler way, Using a NSNumberFormater, or some other API that I might be missing in Apple's documentation.
Thank you!
-
The solution as is right now, that I'm trying to get rid of:
/**
* User inputs a pure, non fractional, numeric string (e.g 1234) We'll see how many fraction digits it needs and format accordingly (e.g. 1234 produces a string such as '12.34' for 2 fractional digits. 12 will produce '0.12'.)
*
* #return The converted numeric string in an instance of NSDecimalNumber
*/
- (NSDecimalNumber *)decimalNumberFromRateInput
{
if (_numericInput == nil ||
_numericInput.length == 0) {
_numericInput = #"0";
}
[self clearLeadingZeros];
if (self.formatter == nil) {
return nil;
}
if (self.formatter.maximumFractionDigits == 0) {
return [NSDecimalNumber decimalNumberWithString:_numericInput];
}
else if (_numericInput.length <= self.formatter.maximumFractionDigits) {
NSString *zeros = #"";
for (NSInteger i = _numericInput.length; i < self.formatter.maximumFractionDigits ; i++) {
zeros = [zeros stringByAppendingString:#"0"];
}
NSString *decimalString = [NSString stringWithFormat:#"0.%#%#",zeros,_numericInput];
return [NSDecimalNumber decimalNumberWithString:decimalString];
}
else {
NSString *decimalPart = [_numericInput substringToIndex: _numericInput.length - self.formatter.maximumFractionDigits];
NSString *fractionalPart = [_numericInput substringFromIndex:_numericInput.length - self.formatter.maximumFractionDigits];
NSString *decimalString = [NSString stringWithFormat:#"%#.%#", decimalPart, fractionalPart];
return [NSDecimalNumber decimalNumberWithString: decimalString];
}
}
If I understand your goal correctly, the solution should be much simpler:
float number = [originalString floatValue] / 100.0;
NSString *formattedString = [NSString stringWithFormat:#"%.2f", number];

Backward with custom string

I used a string array for emoticons like this:
NSArray *emoticons = #[#"[smile]",#"[cry]",#"[happy]" ...]
then in a UITextView displaying a string like this:
I'm so happy now [happy] now [smile]
When I click a backward or delete button, if the last word is in emoticons, I want a whole emoticon string be deleted, not the last one character only.
Any idea?
Try this,
NSString *string = self.textView.text;
__block NSString *deleteWord = nil;
__block NSRange rangeOfWord;
[string enumerateSubstringsInRange:NSMakeRange(0, self.textView.selectedRange.location + self.textView.selectedRange.length) options:NSStringEnumerationByWords | NSStringEnumerationReverse usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) {
deleteWord = substring;
rangeOfWord = enclosingRange;
*stop = YES;
}];
if ([emoticons containsObject:deleteWord]) {
string = [string stringByReplacingCharactersInRange:rangeOfWord withString:#""];
self.textView.text = string;
self.textView.selectedRange = NSMakeRange(rangeOfWord.location, 0);
}
You might achieve something like this with the UITextViewDelegate method textView:shouldChangeTextInRange:replacementText: checking what is about to be deleted and remove the whole [emoticon] word.
I am giving you the idea that i used.
as you do not mentioned what you used as emoticons.
but for delete logic i think you will get idea from my this code.
if ([string isEqualToString:#""]) {
NSString *lastChar = [txthiddenTextField.text substringFromIndex: [txthiddenTextField.text length] - 1];
NSLog(#"Last char:%#",lastChar);
txthiddenTextField.text = [txthiddenTextField.text substringToIndex:[txthiddenTextField.text length] - 1];
NSString *strPlaceHolder;
strPlaceHolder = txthiddenTextField.text;
if([lastChar isEqualToString:#"]"])
{
int j = 1;
for (int i = [txthiddenTextField.text length]-1; i >=0; --i)
{
NSString *lastChar = [txthiddenTextField.text substringFromIndex: [txthiddenTextField.text length] - 1];
if([lastChar isEqualToString:#"["])
{
NSLog(#"%d",j);
txthiddenTextField.text = [txthiddenTextField.text substringToIndex:[txthiddenTextField.text length] - 1];
// NSLog(#"Processing character %#",strPlaceHolder);
break;
}
txthiddenTextField.text = [txthiddenTextField.text substringToIndex:[txthiddenTextField.text length] - 1];
j = j+1;
}
}
NSLog(#"My text fild value :%#",txthiddenTextField.text);
return YES;
}
So, from here you have to check if the closing bracket is coming or not.
if closing bracket will come then up to opening bracket you have to delete.
then whole emoticon will delete.
hope this helps....

Resources