Mimic the iPhones phone keypad input - iphone

How would you go about mimicing the iPhones keypad input. So that when you click one 1 is displayed then 2 then it is 12... so on and so forth along with the ( ) -. I don't want to use the actual phone app because I'm creating a false dialer, but I want it to look and function kind of like the actual thing.
Any ideas would be greatly appreciated thanks.
EDIT:
Ok so I put in all the buttons needed but I ended up making them all individual buttons. THey are all linked including the label and this is what one button and the updater looks like.
-(IBAction)zeroButton:(id)sender{
self.enteredPhoneNumberString = [self.enteredPhoneNumberString stringByAppendingString:[NSString stringWithFormat:#"%d", "0"]];
[self updateFormattedPhoneNumberLabel];
}
-(void)updateFormattedPhoneNumberLabel {
if ([self.self.enteredPhoneNumberString length] > 3) {
NSString *firstThree = [self.enteredPhoneNumberString substringToIndex:2];
NSString *lastSet = [self.enteredPhoneNumberString substringFromIndex:2];
self.label.text = [NSString stringWithFormat:#"%#-%#", firstThree, lastSet];
}
else if ([self.self.enteredPhoneNumberString length] > 7) {
NSString *firstThree = [self.enteredPhoneNumberString substringToIndex:2];
NSString *secondThree = [self.enteredPhoneNumberString substringToIndex:2];
NSString *lastSet = [self.enteredPhoneNumberString substringFromIndex:2];
self.label.text = [NSString stringWithFormat:#"(%#) %#-%#", firstThree, secondThree, lastSet];
}
}
I had also tried it with the "" not being around the numbers being appended. Any idea why nothing is being displayed?
NEW EDIT:
I added enteredPhoneNumberString = #""; and with the numbers formatted the way you original had it displays the numbers. The main issue I'm having now is getting it so that the () and - pop up in the right spots.

I would suggest creating a grid of UIButtons that mimics the numpad, these buttons all call a method such as keyPadButtonTouchedUpInside:(id)sender and have a tag that corresponds to the number it represents.
Implementation of keyPadButtonTouchedUpInside:(id)sender may look like...
- (void)keyPadButtonTouchedUpInside:(id)sender {
UIButton *touchedButton = (UIButton *)sender;
if (touchedButton.tag <= 9) {
self.enteredPhoneNumberString = [self.enteredPhoneNumberString stringByAppendingString:[NSString stringWithFormat:#"%d", touchedButton.tag]];
[self updateFormattedPhoneNumberLabel];
} else {
// maybe some other code for pounds/stars entered on the keypad if you have these
// you will also be checking if the user hit the backspace key and trim your
// phone number string by 1
}
}
Now you need to implement updateFormattedPhoneNumberLabel
This will look at the instance NSString variable self.enteredPhoneNumberString and update a UILabel that you have in place to display the number.
updateFormattedPhoneNumberLabel might look like...
- (void)updateFormattedPhoneNumberLabel {
if ([self.self.enteredPhoneNumberString length] > 3) {
NSString *firstThree = [self.enteredPhoneNumberString subStringToIndex:2];
NSString *lastSet = [self.enteredPhoneNumberString subStringFromIndex:2];
self.formattedPhoneNumberLabel.text = [NSString stringWithFormat:#"%#-%#", firstThree, lastSet];
} else if ....
// more conditions to check for other lengths of the
// entered number and continue with the proposed formatting methods.
Hopefully that gets you down the path, there may be more efficient methods for doing this but in reality its not an intensive operation so I wouldn't worry to much about optimization unless you see some kind of entry lag which I wouldn't expect.
EDIT
I would probably update the formatting conditions so that the formatting happens in the following behavior.
1-3 numbers entered shows as "1", "12", or "123"
4-7 numbers entered shows as "123-4", "123-45", "123-456", or "123-4567"
8-10 numbers entered show as "(123) 456-78", "(123) 456-789", or "(123) 456-7890"
11 numbers entered show as "1+(234)-567-8901"
Anything more than 11 I would just show a string of numbers, unless you want to get into formatting non-us numbers. You should also play around with entering numbers in the Phone App to see how it responds if you want to mimic it completely.

Related

IF statement in Objective-C in Xcode

In Xcode, I'm trying to make a button that changes it's text, relative to what the text currently is. For example: If the button says "1" and it is pressed, I want the text to change to "2" and "2" to "3" and so forth, here's the snippet of code that's giving me trouble:
if (magicButton.titleLabel = #"1") {
[magicButton setTitle:#"2" forState:UIControlStateNormal];
}
Xcode gives me this error "Assignment to readonly property" on line one of the snippet. I'm pretty new to Objective-C and iPhone App development, so maybe it's something crazily obvious and simple. Please don't mind if that's the case.
Here's a paste of my implementation file if it would help at all.
Thanks in advance.
'=' is for assignment while '==' is for comparison. But in the case of string comparison you should use isEqualToString method. Something like this:
if ([magicButton.titleLabel.text isEqualToString: #"1"]) {
[magicButton setTitle:#"2" forState:UIControlStateNormal];
}
PS. Also note that you should get the UILabel's text property
If you want to be changing the button text relative to what it is with no restrictions, you can't make a million if statements. You should get the value of the button title (if it even has a title) and just add 1 to it, like so:
NSString *string = randomButton.titleLabel.text;
if ([randomButton.titleLabel.text length] == 0) { //Check if there is not a title on the button
[randomButton setTitle:#"1" forState:UIControlStateNormal]; //And if there isn't, set it to "1"
}
else {
int yourInt = [string intValue]; //Convert to int
int nextInt = yourInt + 1; //Add one to value
NSString *finalString = [NSString stringWithFormat:#"%d",nextInt]; //Convert back to string
[randomButton setTitle:finalString forState:UIControlStateNormal]; //Finally set it as the title
}

Calculating enough text to fit within existing UILabel

I can't get some CoreText text wrapping code working for me; it's just too complicated. I'm going to try and go another route, which is to split my UILabel into two.
What I'm trying to achieve is to have my text appear to wrap around my fixed sized rectangular image. It'll always be the same dimensions.
So, when the UILabel next to the image fills up exactly, it'll create another UILabel below the image.
Now, how do I calculate the text in the first UILabel and have it fit nicely in the entire width of the UILabel, without being too short or cut off at the end?
Well, this ought to work to get the substring of the master string that will fit within the desired width:
//masterString is your long string that you're looking to break apart...
NSString *tempstring = masterString;
while (someLabel.bounds.size.width < [tempString sizeWithFont:someLabelLabel.font].width) {
NSMutableArray *tempArray = [NSMutableArray arrayWithArray:[tempString componentsSeparatedByString:#" "]];
//Remove the last object, which is the last word in the string...
[tempArray removeLastObject];
//Recreate the tempString with the last word removed by piecing the objects/words back together...
tempString = #"";
for (int i=0; i < tempArray.count - 1; i++) {
tempString = [tempString stringByAppendingFormat:#"%# ", [tempArray objectAtIndex:i]];
}
//You must append the last object in tempArray without the space, or you will get an infinite loop...
tempString = [tempString stringByAppendingFormat:#"%#", [tempArray objectAtIndex:tempArray.count - 1]];
}
//Now do whatever you want with the tempString, which will fit in the width desired...
Of course, this is assuming you want the separation to occur using word wrapping. If you don't mind words themselves being cut apart (i.e. character wrap) in order to fully take up the desired width, do this instead:
NSString *tempstring = masterString;
while (someLabel.bounds.size.width < [tempString sizeWithFont:someLabelLabel.font].width) {
tempString = [tempString substringToIndex:tempString.length - 1];
}
//Now do whatever you want with the tempString, which will fit in the width desired...
In order to get the remaining piece of the string left over, do this:
NSString *restOfString = [masterString substringFromIndex:tempString.length];
Hope this helps. I have to admit that I haven't properly tested this code yet, though I've done something similar in the past...
Try below link its will help you.
If you want to create a "link" on some custom text in your label, instead of using a WebView as #Fabian Kreiser suggested, you sould use my OHAttributedLabel class (you can find it this link)
See the sample code provided on my github repository: you can use my addCustomLink:inRange: method to add a link (with a customized URL) to a range of text (range that you could determine by iterating over every occurrences of the word "iPhone" in your text very easily). Then in the delegate method on OHAttributedLabel, you can catch when the link is tapped and act accordingly to do whatever you need.

Only one comma/point in the calculator! Objective-C for iPhone

I'm putting up a CalculatorApp for the iPhone and there is just one thing that i need to end, the floating-point!
As in normal calculators, i need to do something so that will only permit one "." .
Can you dudes help me?
you have a few ways to go, such as, NSString's rangeOfString method, e.g.
#define FLOATING_POINT_STRING #"."; // set this to #"." or #"," according to the floating point type you want to use
float calculatorText = 45.194; // set this to whatever the label says, or you can skip the float => string conversion as shown below
NSString *text = [NSString stringWithFormat:#"%f", calculatorText];
if ([text rangeOfString:FLOATING_POINT_STRING].location != NSNotFound)
{
// do nothing, there is a floating point
}
else
{
// append FLOATING_POINT_STRING to the label
}
Good luck ;)
Are you using a UIButton for the decimal point button? If so, you could simply disable it as soon as it is pressed. And then of course, re-enable it when "clear" or "equals" or whatever is pressed:
[buttonDecimalPoint setEnabled: NO];

How do I do decimal formatting in Objective-C?

Pretty new to the whole iPhone development scene. I am just practicing, trying to create a basic calculator, I can add simple numbers but I'd like to support decimal places.
Heres my code so far:
- (IBAction) calculate
{
double number1 = ([textField.text doubleValue]);
double answer = number1+([textField2.text doubleValue]);
label.text = [[NSString alloc] initWithFormat:#"%2.f", answer];
}
- (IBAction) clear
{
textField.text = #"";
textField2.text = #"";
label.text = #"";
}
Any help much appreciated.
I think your format might be wrong. What is the output you're expecting, and what are you getting?
If I'm guessing correctly, you may want to try this:
label.text = [NSString stringWithFormat:#"%5.2f", answer];
where the 5 means total digits (in terms of padding for alignment), and the 2 means 2 decimal places.
EDIT: avoiding memory leak, as mentioned in donkim's comment!

How to know the displayed text in UILabel?

I have an UIView containing two UILabels, in order to display a string.
The first UILabel has a fixed size, and if the string is too long and can't hold in this UILabel, I want to display the maximum characters I can in the first UILabel, and display the rest of the string in the second UILabel.
But to make this, I must know the exact part of the string displayed in the first UILabel, which is not easy because of the randomness of the string and the linebreaks.
So, is there a way to get just the text displayed in the first UILabel, without the truncated part of the string?
if ([_infoMedia.description length] > 270) {
NSRange labelLimit = [_infoMedia.description rangeOfString:#" " options:NSCaseInsensitiveSearch range:NSMakeRange(270, (_infoMedia.description.length - 270))];
_descTop.text = [_infoMedia.description substringToIndex:labelLimit.location];
_descBottom.text = [_infoMedia.description substringFromIndex:(labelLimit.location+1)];
} else {
_descTop.text = _infoMedia.description;
_descBottom.text = #"";
}
Okay that's a late answer but maybe it could help someone. The code above is approximatively the solution I used in my app.
_descTop is my first label and _descBottom is the second label. 270 is a constant equivalent to a little less than the average maximum number of characters displayed in my first label, _descTop. I calculated it by hand, trying with many different strings, maybe there's a better way to do that but this worked not bad.
If the string I want to display (_infoMedia.description) is larger than 270 characters, I isolate the first 270 characters plus the end of the next word in the string (by searching the next space), in the case where the 270 characters limit would cut the string in the middle of a word. Then I put the first part of the string in my first label, and the second part in the second label.
If not, I only put the globality of the string in the first label.
I know that's a crappy solution, but it worked and I didn't found any better way to do that.
Following code might help you in getting what you want!!
//If you want the string displayed in any given rect, use the following code..
#implementation NSString (displayedString)
//font- font of the text to be displayed
//size - Size in which we are displaying the text
-(NSString *) displayedString:(CGSize)size font:(UIFont *)font
{
NSString *written = #"";
int i = 0;
int currentWidth = 0;
NSString *nextSetOfString = #"";
while (1)
{
NSRange range;
range.location = i;
range.length = 1;
NSString *nextChar = [self substringWithRange:range];
nextSetOfString = [nextSetOfString stringByAppendingString:nextChar];
CGSize requiredSize = [nextSetOfString sizeWithFont:font constrainedToSize:CGSizeMake(NSIntegerMax, NSIntegerMax)];
currentWidth = requiredSize.width;
if(size.width >= currentWidth && size.height >= requiredSize.height)
{
written = [written stringByAppendingString:nextChar];
}
else
{
break;
}
i++;
}
return written;
}
#end