Changing overlaying labels text on a ScrollView - ios

This is sort of hard to explain so I'm including a picture.
So I have a scrollview (the yellow part) and then an overlaying box with score and how many upgrades the player purchased, etc. The green box with the labels stays in the same position while the yellow part scrolls. That works fine, except I am trying to get the labels to change when the player purchases an item. So lets say the player purchases a pickaxe. The upgrades owned should change from "0/20" to "1/20".
This is my setup. I am using SpriteBuilder by the way. I have a class that handles the scrollview, like the buy buttons and descriptions, etc... Then I have another class just for the overlay on the side, and this is basically the only method in it:
- (void)didLoadFromCCB {
if (_doge < 1000000000000) {
balanceLabel.string = [NSString stringWithFormat:#"%.2Lf", _doge];
} else {
balanceLabel.string = #"A lot!";
}
upOwnedLabel.string = [NSString stringWithFormat:#"%d", _upOwned];
upMaxedLabel.string = [NSString stringWithFormat:#"%d", _upMaxed];
NSLog([NSString stringWithFormat:#"%d", _upOwned]);
}
I've tried a few things and this is the one that I think is "most correct". In the didLoadFromCCB on the scroll class, I have this:
UpgradesScene *upgradesScene = [[UpgradesScene alloc] init];
[upgradesScene didLoadFromCCB];
It's in the correct place (under buy button) but for some reason it doesn't update the label. I do get an NSLog message telling me the level, but for some reason the label doesn't work.
I'm very new to this language so please go easy on me :) Thank you

The problem is that you're creating a new upgradesScene with alloc init rather than getting a reference to the one that's in your scroll view. You should have a property (or IBOutlet if you're making this in IB) that points to that view.

Related

Keep text in UITextView highlighted when the popover is dismissed

I have a UIPopover that shows up a plain view containing a UITextView filled with some text. I have managed to highlight the text. When the popover is dismissed, and re-opened, the highlight disappears. I want to keep the text highlighted even if if the application is closed. Any ideas how to achieve that?The code i used is the following :
- (void)highlight {
NSRange selectedRange = self.textViewAll.selectedRange;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
initWithAttributedString:self.textViewAll.attributedText];
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:selectedRange];
// [highlightedRange addObject:];
// This is where i tried to save each location and length in a mutable array but didn't work
[highlightedRangeLocation insertObject:[NSNumber numberWithInteger:selectedRange.location] atIndex:indexOfHighlight];
[highlightedRangeLength insertObject:[NSNumber numberWithInteger:selectedRange.length] atIndex:indexOfHighlight];
///////////////////////////////////////////////////////////////////////////////
self.textViewAll.attributedText = attributedString;
indexOfHighlight ++ ;
}
- (void)viewDidLoad {
UIMenuItem *highlightMenuItem = [[UIMenuItem alloc] initWithTitle:#"Highlight" action:#selector(highlight)];
[[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:highlightMenuItem]];
float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
if (sysVer >= 8.0) {
self.textViewAll.layoutManager.allowsNonContiguousLayout = NO;
}
}
Could anyone point out how to continue from here?
Edit 1 :
The code that close the popover :
- (IBAction)closeFun:(id)sender {
// self.popoverPresentationController set
[self dismissViewControllerAnimated:YES completion:nil];
// [self dismis]
}
Can't you juste save the Highlighted text range in [NSUserDefaults standardUserDefaults] whenever the popover is dismissed, and retrieve it when the popover reappears ?
I think the problem is in the fact that the popover is responsible for the highlighted state, i.e .it is the popover who keeps that fact/state.
The popover is a part of presentation layer / user interface. Surely the highlight represents some fact that ( now comes the catch ) - is completely independent of the popover.
For example highlighting a task could represent that the task is due. Or, highlighting a label to red color could mean that the balance in the bank is in negative numbers.
You see, no matter what user interface element you use, they only represent some underlying business reality.
But what probably happens you create a popover instance, you set it to have a highlighted element. But then this concrete popover instance dies, when it is closed.
And the highlight dies with it.
When you click some button (I guess), a popover shows up, but it is a different instance. This instance doesn't know about highlight.
Even if you somehow managed to keep the one instance of popover alive, and just hide and show it again, the popover should NOT be responsible to know whether something is red or due, (and thus highlighted.)
In you application, you should have a well separated model layer...which is basically a set of related objects that represent state ie. fact that are related to what the application solves from business perspective (for ex. draws lines, calculates interest..stores music..anything really). This model layer, some object in it, should store the facts..ie.e. the task is due, or the balance is low.
Every time you show your popover, you should investigate what are the underlying facts in your model layer right when the popover is being shown. Ivestigating means find a programmatic way to look into model objects, find out about values there and and set up the highlight in that moment again based on this "investigation". You should not rely on the fact that it was highlighted in the not so distant past.

UIImageView center not updating properly

I'm practicing some iOS programming. I'm looking to move a UIImageView object to a given position on the screen. The storyboard contains
-Three textboxes to input X Y and Z components (xbox,ybox,zbox)
-Three labels to display said component values (XLabel,YLabel,ZLabel)
-UIImageView containing an image (ball)
-Go button (calls buttonPressed when pressed)
The following code successfully moves the image after inputing values into the textboxes n clicking "GO". However, when I uncomment the code to update the labels, the image does not move until I click "GO" twice in a row. The first time, the labels updates. The second time, the image updates. Why does it require two clicks when I have the label update code uncommented?
Thanks,
Rob
- (IBAction)buttonPressed {
[self graph: [xbox.text intValue] :[ybox.text intValue] :[zbox.text intValue]];
/*
XLabel.text = [NSString stringWithFormat:#"X:%#", xbox.text];
YLabel.text = [NSString stringWithFormat:#"Y:%#", ybox.text];
ZLabel.text = [NSString stringWithFormat:#"Z:%#", zbox.text];
*/
}
...
-(void)graph:(int)xpos : (int)ypos : (int)zpos{
ball.center = CGPointMake(xpos,ypos);
}
I'm going to provide this as an answer. Turn off auto-layout.

Data from DetailViewController not displaying

I'm making a chemistry calculator segment in an app I'm working on, and I cannot get the data and I cannot get the information to correctly populate the screen. There is a secondary issue, the alignment, and if someone can help me with that I'd greatly appreciate it, but it isn't the primary focus of this question - I'll make a dedicated topic for it.
So I'll go over what I want to do, and what I've tried. What I'm trying to do is make a chemistry calculator where depending on what equation is selected, a UIStepper max/min.Value is modified to include all possible derivations of that equation, as well as certain UILabels and UITextFields shown/hidden.
I have confirmed that I have data passed down from the MasterViewController as I've set the data to an NSString called _equation, and successfully used _equation to modify the title of the DetailViewController under self.title in viewDidLoad.
I have tried placing and initializing all UIStepper properties appropriately under a if/if else nest under viewDidLoad (which also quantizes the _equationName possible values to an integer (eqNum) so that it can be used in a switch statement). I have also tried placing the UITextField hidden properties under viewDidLoad, to no avail.
So without further ado, let's get to the code. I've truncated the code down to one equation so you can see what's going on here easier - note that this is nested under the IBAction for the Calculate button:
// Take _equationName quantization and use it in a switch case to determine the formula that IBAction will use:
if (dflt)
{
switch (eqNum)
{
case 1:
if ((stepper.value = 1))
{
// Change deriv_units appropriately:
deriv_units.text = #"Energy (Joules)";
// This is a Planck's constant calculation, we hide the second variable as the constant
// is stored:
value2.hidden = YES;
value2_type.hidden = YES;
// Now we set up the parameters of the first entry variable:
value1_type.text = #"Frequency (in Hz)";
double frequency = [value1.text doubleValue];
double Planck = 6.626069e-34;
double energy = Planck * frequency;
// Now we set up the return field to return results:
NSString* resultIntermediate = [NSString stringWithFormat:#"%f", energy];
result.text = resultIntermediate;
units.text = #"J";
}
and the subsequent code under viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
self.title = _equationName;
int eqNum;
if ((_equationName = #"Energy-Frequency Relation"))
{
eqNum = 1;
// Set stepper bounds for derivation:
[stepper setMinimumValue:1];
[stepper setMaximumValue:3];
self.stepper.stepValue = 1;
self.stepper.wraps = NO;
self.stepper.autorepeat = NO;
self.stepper.continuous = YES;
// This is primarily a two-variable equation, so hide UITextView and UILabel #3:
value3.hidden = YES;
value3_type.hidden = YES;
}
(Props to anyone who recognizes this - it's Planck's relation! :D)
Here is what the GUI is supposed to look like (as it appears in Storyboard):
Here is what it comes out looking like in the iOS Simulator:
Note the misalignment issue, which isn't the principle issue in play here.
Also note that right now, the switch statement for equation parameters is under an if tree that checks to see if dflt (a Boolean variable assigned to UISwitch) returns true for double-precision calculations. However, upon toggling the switch ON, the issue does not correct.
Here's an even more complete explanation:
value#.text is the number entered in one of the three UITextFields, from top to bottom.
value#_type is the text to be displayed in the corresponding UILabel.
deriv_units is the UILabel below the one marked "Derivation Units", and is used to display which derivation of the equation has been selected using the UIStepper.
At bottom: The rightmost UILabel is the result label, whereas the leftmost is the units label.
Many thanks to anyone who can help this beginning developer along the path of programming righteousness.
About your alignment issue: it looks as though you are creating the storyboard for 4" screen, while running it on a 3.5" screen. In the storyboard onnthe lower right there are some small buttons, one of thise allows you to change instantly between the display for either 4" or 3.5".
Have you made sure your controls are connected to your code?
- (void) viewDidAppear: (BOOL) animated{
[super viewDidAppear: animated];
// some rude NSAsserts, but let's be sure
NSAssert(value1_type != nil, #"Your control element is nil, it might not be hooked up");
// you should now see this text in the textfield
value1_type.text = #"Frequency (in Hz)";
NSAssert(result != nil, #"Your control element is nil, it might not be hooked up");
result.text = #"some test text";
NSAssert(units != nil, #"Your control element is nil, it might not be hooked up");
units.text = #"J";
}

cocos2d: why isn't label appearing?

Hello I am making a side scrolling cocos2d game and I want a label to show how far the user has flown in the game. For some reason with the code I wrote the label is not appearing. Here is my GameEngine class that calls the class method that is supposed to make the label appear:
//Set the meterDistance
meterDistance = [MeterDistance createTheMeterDistance];
[self addChild:meterDistance z:10];
Here is the code in the MeterDistance class:
meters = 1;
meterLabel = [CCLabelBMFont labelWithString:#"0" fntFile:#"green_arcade-ipad.fnt"];
meterLabel.position = ccp(200, screenHeight - 100);
[self addChild:meterLabel z:10];
meterLabel.anchorPoint = ccp(1.0, 0.5);
[self schedule:#selector(updateLabel:)interval:1.0f/20.0f];
Here is the updateLabel method:
-(void)updateLabel:(ccTime)delta{
meters++;
NSString* scoreString = [NSString stringWithFormat:#"%d", meters];
[meterLabel setString:scoreString];
}
It's been a while since I last dealt with cocos2d code...
What you've written looks ok.
Take it one step at a time and see where it goes wrong.
Position your label in the middle of the screen (maybe screenheight is off, or anchorPoint moves the label outside of the screen).
Another possible cause is if the font file name is not exactly #"green_arcade-ipad.fnt".
Maybe you missed a capital letter?
Otherwise maybe some other element of your layer could be obstructing the label.

Reloading a non-table view (iOS)

I'm working on a painting app, and I want to user to be able to switch through paintings that are saved as PNGs to the documents directory. I've made an IBAction that does this:
-(IBAction)switchPage:(id)sender{
if ([sender tag] ==1)
{
currentImage=currentImage-1;
}
else
{
currentImage++;
}
[[NSUserDefaults standardUserDefaults] setInteger:currentImage forKey:#"currentDoc"];
[self.view setNeedsDisplay];
}
Just to let you know, I have 2 buttons, a back and forward, and they're connected to the same IBAction that's pasted above. The back button has a tag of 1, and the forward button doesn't have a tag. currentImage is an int that is used to set an image's name, so if currentImage =1, then it would set the image to image1. But that's not what I'm having trouble with, I'm having trouble "reloading" the view. I'm using setNeedsDisplay, but it's not working, and I know that reloadData is only for UITables, so what else could I use?
I've been searching for an answer, but none of the existing questions about this don't have a clear answer, or are under different circumstances.
Thanks for your time and/or dealing with a stupid question, as I'm new to Xcode.
-Karl
I see no view code in your post.
Assuming you have a UIImageView that is displaying the image you would just do:
myImageView.image = whateverUIImage;

Resources