adding numbers in uitextfield to update uilabel - uitextfield

I have code with several uitextfields that will be used to input numbers, and I want to add these numbers together to update a uilabel.
I can do all the updating and the labels and fields, but can't get the addition to work.
Just now I have:
label.text = (textfield1.text + textfield2.text);
I assume I need to convert these textfield inputs to an int, but not sure how to do that...

there is a couple of extra steps you have to do:
convert the string value of your text filed into numerical value
do the math there
and convert it back.
For example (i use float in my case, you can change that to whatever type you want):
float textField1Value = [textfield1.text floarValue];
float textField2Value = [textfield2.text floarValue];
label.text = [NSString stringWithFormat:#"%f", textField1Value + textField2Value];
Hope that helps.

Related

How do I limit NSTextView to 2 lines?

I'm trying to specify the number of lines for NSTextView. My designer is requesting 2 lines of text max. I've tried NSMutableParagraph style to add the ellipses truncation that I want, but with NSMutableParagraph I can only get NSTextView with 1 line and without NSMutableParagraph, I get a scrolling text with as many lines as needed to complete text.
var attributedString = NSMutableAttributedString(string: "This is my text, I can keep going for many characters")
var para = NSMutableParagraphStyle()
para.lineBreakMode = NSLineBreakMode.ByTruncatingTail
let globalAttributes = [
NSParagraphStyleAttributeName: para
]
let range = NSRange(location:0, length: attributedString.length)
attributedString.addAttributes(globalAttributes, range: range)
cellView.myTextView!.textStorage?.setAttributedString(attributedString)
I've tried height constraint on NSTextView. I've tried:
cellView.myTextView!.textContainer?.containerSize = NSMakeSize(300, 32)
I've tried creating IBOutlet for NSScrollView that NSTextView in within and adjusting its height. No luck with getting both 2 lines and truncation. Any help is greatly appreciated. I feel like I'm just missing a method or setup. Thanks!
From 10.11 you can use this
yourTextViewObj.textContainer.maximumNumberOfLines = 2;
You can use an NSTextField configured as a multi-line label. That means setting its cell's wraps property to true and, if desired, its truncatesLastVisibleLine to true.
For NSTextField (aka label) You can just do self.textField.maximumNumberOfLines = 2;
That's it.
Max number of lines is now a property of NSTextField
label.maximumNumberOfLines = 1;

UITextField not scrolling horizontally

I am trying to make a small calculator app.
When a UIButton is pressed, the Button title is added to a UITextField.
kind of:
myuitextfield.text = [myuitextfield.text stringByAppendingString:[button currentTitle];
When I reach the end of my textfield, the text gets truncated. How can I disable this, so the textfield starts scrolling automatically and allows adding more characters?
I tried every possible option in Interface Builder, without any luck.
Isn't the UITextField supposed to scroll automatically? I can see this behavior when a native keyboard is used and text is entered.
I have chosen UITextField, as I need only 1 Line.
To illustrate the Problem:
When I enter text using my custom UIButtons text gets truncated
When I tap the UITextField and enter text using the keyboard I can enter unlimited text and the text is not truncated.
If you are facing this issue on iOS7, I've managed to fix it after been inspired by this post. In my case I had a field for entering an email address and after reaching the edge, the user could carry on typing but the text would be invisible (off-field).
First, add a callback to your UITextField so that you can track a text change to the field:
[self.field addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
Then evaluate the size in pixels of the entered string as it is typed and change the text alignment from left to right when reaching the edge of the field area:
- (void)textFieldDidChange:(NSNotification *)aNotif{
float maxNumPixelsOnScreen = 235; // Change this value to fit your case
CGSize maximumSize = CGSizeMake(maxNumPixelsOnScreen + 10, 1);
NSString *aString = self.field.text;
CGSize stringSize = [aString sizeWithFont:fieldFont
constrainedToSize:maximumSize
lineBreakMode:NSLineBreakByWordWrapping];
self.field.textAlignment = NSTextAlignmentLeft;
if (stringSize.width >= maxNumPixelsOnScreen)
self.field.textAlignment = NSTextAlignmentRight;
}
Note:
self.field is the offending UITextField
maximumSize: I'm adding 10 the the width to be slightly over the limit defined
fieldFont is the UIFont used to render the text field
Hope it helps!
you have to add UITextview and limit the number of lines to 2.Textfield doesnt work with two lines.Textview is same as textfields except the delegates and some properties differ.

Core Plot, It takes a long time to display a label on top of each bar column

I'd like to display a label on top of each bar column with the delegate method:
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot
recordIndex:(NSUInteger)index {
CPTMutableTextStyle *textStyle = [CPTTextStyle textStyle];
textStyle.color = [CPTColor whiteColor];
textStyle.fontSize = 12.0f;
CPTTextLayer *textLayer = [[[CPTTextLayer alloc] initWithText:#"x" style:textStyle]
autorelease];
return textLayer;
}
In case that it is my project that brings this problem, I directly insert this code snippet into the CPTTestAppBarChartController.m file in the CPTTestApp-iPhone project downloaded from
here.
But it still takes about 2 mins to display the labels. How can I make it display faster?
Thanks.
How much data are you plotting? If it's a lot (100's of points), you might want to only create labels for the visible points. Reload the data using the -reloadDataInIndexRange: method to load new labels when new data moves into the visible range.
You can also create the text style once and store it in a static local variable or an ivar instead of creating a new one for every label. That will save a little bit of time if you have a lot of labels.
P.S. Be sure to use [CPTMutableTextStyle textStyle] instead of [CPTTextStyle textStyle] to create the text style.

string/number from TextField to be used for calculation?

sorry for my question and for the long explanation following here, probably there's a simple solution for someone who is experienced in Cocoa and Objective-C, but I'm just starting few weeks ago and I can't figure out how to get this thing working, Grrrrrrr!!
OK, let's put it like this, in my window I have the following:
2 TextField(NSTextField) called:
blockOffText
blockOnText
1 Label(NSTextField) called:
flightTimeText
1 button(NSButton) called:
updateButton
What I want to do is all about time calculation I guess, get the "start-time" in one TextField and the "end-time" in the other.
One is supposed to be the "takeoff-time" and the other the "landing-time" or for example the "duty-startTime" and "duty-endTime"...it's the same!
Then I want to calculate the "flight-time" or "duty-time" and show it in the Label.
At the end I will also need to store the value or the time in a database as an integer, the value should be represented by all minutes corresponding to each time, but the database part is not a problem at the moment.
Maybe I can write the number in the TextField without the format but just the number and get the time show-up formatted in some way?
I would like to write for example "1245" and "1525" without having the needs to put the ":" between the hours and minutes, then can I get the value formatted "12:45" "15:25" in the TextField in some way? Maybe after pressing the button?
Ok, that is a second problem anyway, my real problem is I need to get the value I wrote in the TextField ("1245" and "1525") to be assigned to some variables in the program that I called "BlockOff" and "BlockOn".
I need to transform them in an integer that represent the minutes corresponding to their value..example:
The 1245 will become 765 minutes...(12 times 60 + 45)
and 1525 will become 925 minutes...(15 times 60 + 25)
HOW CAN I DO THIS?
In this way I can use the minutes to calculate the difference to get the flight time or even add flight time to other flight time.
At the moment my program works a little bit differently... like this:
If I directly assign the value to the two variables:
int blockOff = 765;
int blockOn = 925;
then I can calculate and show in the two TextField the takeOff and landing time formatted like I want: "12:45" "15:25"...I use other 2 variables to do so:
int oreBlkOff, minBlkOff = 0;
minBlkOff = blockOff % 60;
oreBlkOff = (blockOff - minBlkOff) / 60;
Then I can show the value in the TextField:
[blockOffText setStringValue:[NSString stringWithFormat: #"%d:%d", oreBlkOff, minBlkOff]];
Same with blockOnText and flightTimeText, so there is no problem there, but this is not really what I need right?
HOW CAN I GET THE VALUE OF THE TEXTFIELD AND STORE THE VALUE IN VARIABLES THAT CAN BE USED TO DO CALCULATION?
HOW DO I GET THE FIRST TO DIGITS AND LAST TO DIGITS FROM THE VARIABLES SO I CAN USE THEM AS HOURS AND MINUTES FOR MY CALCULATION?
I WOULD LIKE TO BE ABLE TO TYPE THE VALUE IN THE TEXTFIELD, PRESS "ENTER" OR "RETURN" AND GET THE VALUE ASSIGNED IN THE VARIABLE.
IS THIS THE CORRECT WAY OR I'M JUST GOING THE WRONG WAY IN THIS.
IN ANOTHER PROGRAM I DID IN VISUAL BASIC THAT WAS THE WAY I USED.
THANK YOU VERY MUCH IN ADVANCE FOR YOU HELP!
Gianluca
To get the int value from text field you'd use integerValue or floatValue for float. But you should definitely check out the date/time controls in cocoa.
Ok, if I didn't miss the point of your long question...
You have a text field with something like #"2345:8743" and you want to get the two numbers in int variables (a=2345, b=8743).
First you need to get these two text representations of your numbers in two NSStrings. You can do it like this:
NSString * yourString = #"2345:8743";
NSString *stringA = [yourString substringToIndex:4]; //stringA = #"2345"
NSString *stringB = [yourString substringFromIndex:5]; //stringB = #"8743";
Now to get the in values, just do:
int a = [stringA intValue];
int b = [stringB intValue];
Let me know if that is helpful to you.

Retain a random number across different functions in Cocoa?

I know how to do a global variable, but whenever I try to define a global variable with a random number function, xcode says "initializer element is not constant." The compiler doesn't want to make a variable from a random number because the random number function is not constant.
How do I generate a random number and then use that same value for more than one action? (For example, to define a color and then write that value to a label?)
Code:
#import "Slider_with_IBAppDelegate.h"
float * const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);
//^this is where I get the error: "initializer element is not constant"
#synthesize label
//write value to label
- (IBAction) doButton {
label.text = [NSString stringWithFormat:#"%f", hue];
}
//set background color
- (void)applicationDidBecomeActive:(UIApplication*)application
{
self.label5.backgroundColor = [UIColor colorWithHue:hue
saturation:1.0
brightness:1.0
alpha:1.0];
}
----edit------
Thanks for the suggestions. It still doesn't work for me, though, what am I doing wrong?
New code:
#import "Slider_with_IBAppDelegate.h"
float const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);
//^I still get the error: "initializer element is not constant."
#synthesize label
//write value to label
- (IBAction) doButton {
label.text = [NSString stringWithFormat:#"%f", hue];
}
//^this is where I get the error "'hue' undeclared (first use of this function)"
//set background color
- (void)applicationDidBecomeActive:(UIApplication*)application
{
hue = ((arc4random() % ((unsigned)1000 + 1))/1000.0);
/*here I get the error "assignment of read-only variable 'hue.'"
If I insert "float" just before hue, I do not get this error,
but it still won't compile because of the error above.*/
self.label5.backgroundColor = [UIColor colorWithHue:hue
saturation:1.0
brightness:1.0
alpha:1.0];
}
Make it non-const and initialize it in applicationDidBecomeActive. Is there a reason it must be constant?
I know how to do a global variable, but whenever I try to define a global variable with a random number function, xcode says "incompatible types in initialization."
float * const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);
That's not a function; it's an expression. I'd be surprised if you're not also getting an error here, because you can't initialize a global variable with an expression that isn't constant. As alltom.com says, you need to assign to it from applicationDidBecomeActive:.
The warning is because you've given the variable a pointer type (float *), but you're not assigning a pointer to it. Cut out the asterisk, because you're not going to put a pointer in this variable.
Xcode doesn't want to make a variable from a random number because the random number function is not constant.
Xcode doesn't care one way or the other. It's just reporting the findings of the compiler. By default, the compiler for Objective-C is GCC, but Xcode supports other compilers (and Xcode does come with one other C/Objective-C compiler: LLVM-GCC).
… I couldn't call the same value for the label.
You're not showing a label here, and you can't call a value. You can only call a function, and you don't have one in the code shown.
It gave me the error "function undefined: first use of this function" in doButton even though it was defined in applicationDidBecomeActive.
No, it wasn't. Assigning to a variable does not create a function.
In case anyone is wondering, I finally found a way to do this effectively. (I am sure this is what alltom was saying, I was just too dumb to understand.)
I declared a float and a seed in my .h file:
- (float)generate:(id)sender;
- (void)seed;
And in the implementation file, I defined the float as a random number, and I used srandom() as a random seed generator.
- (float)generate:(id)sender
{
//Generate a number between 1 and 100 inclusive
int generated;
generated = (random() % 100) + 1;
return(generated);
}
- (void)seed {
srandom(time(NULL));
}
Then anywhere I wanted to retain a random number, I used
srandom(time(NULL));
generated1 = ((random() % 100) + 1)/100.0;
to initiate the number, and from there I was able to use generated1, generated2, hue, etc. as variables in any function I wanted (and I made sure to declare these variables as floats at the top of the file).

Resources