iPhone - how to select from a collection of UILabels? - ios

I have a few UILabels, any one of which will update according to the index of an NSArray index they represent. I thought of selecting them by their tag
self.displayLabel.tag = myArray[index];
but that changes the tag value to whatever my array is holding at the moment
Using a dictionary for whatever tricks it offers instead of an NSArray doesn't help because i still have to select the correct matching label. This is the effect i want to achieve.
self.|mySelectedLabel|.text = myArray[index];
what should i put in |mySelectedLabel| to get the one i'm looking for?
I'm almost ashamed to ask at my reputation level, but this is stymie-ing me
every search only turns up how to set Labels and change, not the process of selecting

Assuming you have set the tags to the appropriate index to match your
array indices you can use [self.view viewWithTag:index];

Why are you not setting the tag with:
self.displayLabel.tag = index;
Also, you could just loop though an array of labels and find the right one:
for (UILabel *label : labelArray) {
if (label.tag == index) {
label.text = #"I found you!";
}
}

Rather than using tags you can refer to your specific textfields by reference:
// Create an array to hold your textfields
NSMutableArray *textFields = [NSMutableArray array]
// Create your textfields and add them to the array
UITextField *textField;
for (NSUInteger idx = 0: idx++; idx < numberOfTextFieldsYouWant) {
textField = [UITextField alloc] initWithFrame:<whateverYouWant>];
[textFields addObject:textField];
}
Since you are adding the objects to an array, rather than using the tag value 0, 1, 2... you can just access it by it's index in the array
So, for what you want to do you can just do:
textfields[index].text = myArray[index];
It's a lot cleaner, doesn't rely on magic tags, and you have an array of all your dynamic textfields that you can remove, or change in one place.
I think tags are vastly overused, and they aren't necessary in most cases.

Just letting you know I reframed the problem and this eventually worked for me without having to use an array
( with endless experimenting, I sort of bumped into it so I don't know if it constitutes good technique )
the desired label corresponding to the bag weight ( one of a number possible ) displays the right update
- (IBAction)acceptWeight:(UIButton *)sender {
int tempValue = (int) currentWeight;
// current weight comes from a UISegementedController
for (UILabel *labels in self.view.subviews)
{
if (labels.tag == currentWeight)
{
bags[tempValue]++;
labels.text = [NSString stringWithFormat:#"%i",bags[tempValue]];
}
}
totalKilo = totalKilo + (int)currentWeight;
self.totalKilo.text = [NSString stringWithFormat:#"%d",totalKilo];
}

Related

Adding label text together

Hi im relatively new to iOS and I'm just wondering how i would add two labels together.
- (IBAction)switch1
{
if (switch1.on) {
value1.text = #"3";
} else {
value1.text = #"0";
}
}
- (IBAction)switch2
{
if (switch2.on) {
value2.text = #"3";
} else {
value2.text = #"0";
}
}
As you can see i have used two switches which would show two different values if they were turned on or off.
Could someone help me understand how i would add two values together.
I.e if switch one was on and switch two was off the value would be three i want this value to be shown in another label.
So far i have come up with this but for some reason it doesn't work, i have a feeling it is the format specifier but I'm not sure.
int sum = [[value1 text] intValue] + [[value2 text] intValue];
value3.text = [NSString stringWithFormat:#"%d", sum];
Dont you have this:
int sum = [[value1 text] intValue] + [[value2 text] intValue];
value3.text = [NSString stringWithFormat:#"%d", sum];
in ViewDidLoad or something? Because you have to call this at the end of both IBActions. If you don't, your final value will never change.
Make sure you properly created an outlet connection in Interface Builder as described here:
Creating an Outlet Connection
In short words. Ctrl+Click & Drag from the UISwitch to File’s Owner and click the new switch1 or switch2 action. Create outlets for the text fields and switches and link them.
Set breakpoints in switch1 and switch2 methods and ensure there are being called.
Use po command in the console to check if the text fields and switches are configured correctly.
For example:
po _textField1
should print text field's description. It will print nil when the text field is not there - not linked to a control in interface builder.

how can i differentiate and refer to various UITextViews that are created programmatically?

A UITextView is created each time i click on ADD button. Y-axis value is altered(say, y+=100) every time i click ADD and so a set of UITextViews are created one below the other. I cant figure out how to differentiate and access a particular UITextView. Thanks for any help!
EDIT:
-(IBAction)access:(id)sender
{
int tg=[sender superview].tag;
UIView *view=(UIView *)[textView viewWithTag:tg-1];
}
tg-1 because im trying to access the previous UITextView and when i do this it returns NULL.
Store them on a NSMutableArray:
NSMutableArray * views = [[NSMutableArray alloc] init]
Your IBAction
-(IBAction)access:(id)sender{
int tg=[sender superview].tag;
UIView *view=(UIView *)[textView viewWithTag:tg-1];
[views addObject: views];
}
Then you can get all the references with a integer index with:
UIView * storedView = [views objectAtIndex: 1];
Use a view tag to differentiate the views and access them.
You don't say how you're creating the new views, but something like this should work:
UIView* new_view = [UITextView initWithFrame(...)];
new_view.tag = generate_tag()
Where the generate_tag() function generates whatever naming scheme makes sense for your application.

Loop in a variable of type IBOutlet

I have twelve text fields as you can see below:
IBOutlet UITextField *ce_1;
IBOutlet UITextField *ce_2;
IBOutlet UITextField *ce_3;
....
IBOutlet UITextField *ce_12;
All I have to do is to set an existing object in an array in each of the variables that are responsible for the text fields, I'm currently doing as follows:
ce_1.text = myArray[1];
ce_2.text = myArray[2];
ce_3.text = myArray[3];
....
ce_12.text = myArray[12];
Not to be writing a lot, I thought I'd put this in an automated way within a loop as follows:
for(i=1;i<13;i++){
ce_[i].text = myArray[i];
}
But this command does not work the way I expected, so I would like your help to try to solve my idea and put it into practice, is there any way of doing this?
Research and start using IBOutletCollection. It will give you an array of text fields that you can build in your storyboard XIB.
Note that you may need to consider the order of the array, and that you might want to sort it (possibly based on the tag of each view).
Technically, you could use string formats and KVC to do what you're currently trying to but it is far from ideal.
You can't just replace ce_1 ce_2 ce_3 with ce_[i] it doesn't work that way. You can only use [number] with an nsarray variable (or decendents).
for example:
NSArray* myArray = #[#1];
NSLog(#"%#", myArray[0]);
You might want to look into IBOutletCollection in order to achieve something similar to what you're looking for.
However, contrary to other answers here IBOutletCollection are ordered by how you link them in the interface builder.
Refer to this for IBOutletCollections: How can I use IBOutletCollection to connect multiple UIImageViews to the same outlet?
You can use IBOutletCollection. You can also use key-value coding:
for(NSUInteger i = 0; i < 13; i++)
{
[[self valueForKey:[NSString stringWithFormat:#"ce_%u", i]] setText: myArray[i]];
}
This will give you what you want.
The way I like to handle these situations is creating a temporary array containing all the text fields:
NSArray *allFields = #[_ce_1, _ce_2, _ce_3, ...];
NSInteger i = 0;
for (UITextField *tf in allFields)
{
tf.text = myArray[i];
i++
}
IBOutletCollection also work but sometimes it gets hard to figure out when you come back to your project which label is #3 or #5 and such... I find this works better for me usually :)

How do I use a UIButton to change a label multiple times?

I want to have one UIButton that will change the text of a label in a series. For example, I may have a label that says hello.
Then when i push a button, it will change to, What's up?.
But then a second tap of the same button will change the label to Nuttin' much!.
I know how to make the text of a label change once, but how do I change it many times with the same button? Preferably, anywhere around 20 to 30 separate texts.
Thank you in advance! :D
That's pretty open ended. Consider adding a property to your class which is an index into an array of strings. Each time you push the button increment the array (modulo size of array) and use the corresponding string to update the button. But there are a lot of other ways you could do this...
What happens when the app runs out of phrases? Start over? The typical approach would look like this.
#property (strong, nonatomic) NSArray *phrases;
#property (assign, nonatomic) NSInteger index;
- (IBAction)pressedButton:(id)sender {
// consider doing this initialization somewhere else, like in init
if (!self.phrases) {
self.index = 0;
self.phrases = #{ #"hello", #"nuttin' much" }; // and so on
}
self.label.text = self.phrases[self.index];
self.index = (self.index == self.phrases.count-1)? 0 : self.index+1;
}
In the viewDidLoad method, create an array with strings to hold the labels. Then create a variable to keep track of which object should be set as the current label. Set the initial text:
NSArray *labelNames = [[NSArray alloc] initWithObjects:#"hello",#"what's up?", #"nuttin much"];
int currentLabelIndex = 0;
[label setText:[labelNames objectAtIndex:currentLabelIndex]];
Then in the method that gets called when the button is tapped, update the text and the index.
- (IBAction) updateButton:(id)sender {
// this finds the remainder of the division between currentLabelIndex+1 and labelNames.count. If it is less than the count, its just the index. If its equal to the count we go back to the beginning of the array.
currentLabelIndex = (currentLabelIndex+1)%labelNames.count;
[label setText:[labelNames objectAtIndex:currentLabelIndex]];
}

Keeping track of objects on the screen

Even though I’m writing in Objective C, most of my code is still written in a procedural style. However, now I want to do something where that approach will not work. So I need some advice on how to deal with an indeterminate number of objects on the screen at the same time. I’m sure that this problem has been solved, I just haven’t been able to find out how.
I have a bunch of games where I put two or four pictures on the screen and then the user interacts with the picture. When they are done with a page they swipe to the next one and I use a transition to slide the pictures off the screen. I can control the movement of the pictures because when they were created I name them self.picture_1 and self.picture_2. The movement method knows about them even though that method didn’t create them.
Now suppose I want to have an indeterminate number of pictures on the screen. I can’t call them self.picture_1. through self.picture_n because ObjectiveC won’t let you dynamically create variable names. But I still need to move them in a method where they weren’t created.
I can make it work with two techniques, neither of which seem ideal. First, I look at all the objects on the screen and then do something with the ones that I want to target. Note: pictures are in buttons.
for ( id subview in self.parentView.subviews ) {
if ( [subview isKindOfClass:[UIButton class]] ) {
UIButton *pictureButton = subview;
for (NSUInteger i=0; i<self.totalItems; i++) {
NSUInteger row = (i % 2) + 1;
NSUInteger column = (i/2) + 1;
NSString *pictureTitle = [NSString stringWithFormat:#"pictureR%iC%i", row, column];
if ( [pictureButton.titleLabel.text isEqualToString:pictureTitle] ) [pictureButton removeFromSuperview];
}
}
}
This works for removing them from the view, but gets cumbersome when I try to make the pictures slide off the screen.
The second way is to make an array that holds the picture objects when they are created. I’ve been playing with something like this.
self.gridImages = [NSMutableArray arrayWithCapacity:4];
for (NSUInteger i = 0; i < itemsOnScreen; i++) {
Word *word = [wordListArray objectAtIndex:i];
self.gridImages[i] = word.image;
}
And then to do things with the pictures I loop through the array.
for (NSUInteger i = 0; i < itemsOnScreen; i++) {
Picture *picture = self.gridImages[i];
// do something with picture
}
Neither of these methods seems ‘right’ so I’m wondering if there is a preferred method for manipulating an indeterminate number of objects on the screen?
#Hot Licks, that works, so I put you answer into an answer.
I have it working for checkBoxes. They are created by the main view controller and it passes in a tag. I'm using tags starting at 1000 for checkboxes, 2000 for pictures, etc. Just before I put the checkBox on the screen, I assign it the tag.
[self.checkBox setTag:checkBoxTag];
You could also use: self.checkbox.tag = checkBoxTag;
When it is time to remove the checkBoxes, I loop through all of the tags starting at 1000 up to the total number of items on the screen. I have warnings turned up to 11 so I need to cast the counter to an NSInteger.
- (void)removeCheckboxes {
for (NSUInteger i = 0; i < self.totalItems; i++) {
NSInteger tagNumber = 1000 + (NSInteger)i;
[ [self.parentView viewWithTag:tagNumber] removeFromSuperview];
}
}

Resources