THIS QUESTION HAS BEEN RE-WRITTEN IN ORDER TO PROPERLY COMMUNICATE THE INTENTIONS OF THE AUTHOR
I have a MasterDetail App that will eventually become a way to track an amount of "players" through a fixed amount of "challenges" (60 to be exact). The challenges are the same for every player, while the status of each player on the individual challenges may vary. All of the data about the players are being stored on a Postgres Database and then fetched using the JSONModel in the LeftViewController. I am getting all of the data correctly from the DB and I have successfully put it into a NSMutableDictionary. The data in the Dictionary looks like this (this is one player):
player = (
{
id = 9;
name = "Arthur Dent";
currentChallenge = "Cooking";
timeStarted = "04 Jul 2013 1:08 PM";
challengesDone = (
{
challengeName = "Flying";
timeCompleted = "04 Jul 2013 12:08 PM";
}
);
nextChallenge = "Swimming";
freePass = (
Running,
"Climbing"
);
},
As you can see, the player has some challenges "done" ("done"), some he has doesn't need to do ("pass") on, one he is doing ("currentChallenge") and the one challenge that he will do next ("nextChallenge"). For each of these states that a player can be in, I want the "Challenges" that are in the RightViewController to be color coded so you can understand what is happening at a glance. I need the "challenges" to light up different colors, based on the status of the player, which is determined by the data that is in my NSMutableDictionary.
By creating arrays from the data in the NSDictionary I can get the colors to change by doing this:
if ([freePassArray containsObject:#"challenge three name"])
{
UIImage *image = [UIImage imageNamed:#"status_pass.png"]; //status_pass.png is my color
[challengeThreeImageView setImage:image];
}
But if I did it like this, I would have to write 240 if and else if statements to cover all possible statuses on all 60 challenges.
My arrays only contain the data of the player selected because I pass the data over like so:
*LeftViewController.m * didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//Re-fetch the feed from the Postgres Database when a user selects an entry
[JSONHTTPClient getJSONFromURLWithString:#"http://myurl" completion:^(NSDictionary *json, JSONModelError *err) {
NSError* error = nil;
_feed = [[PostgresFeed alloc] initWithDictionary:json error:&error];
[[NSNotificationCenter defaultCenter] postNotificationName:#"myNotification" object:nil userInfo:[[json objectForKey:#"preclear"] objectAtIndex:indexPath.row]];
}];
Player *selectedPlayer = [_players objectAtIndex:indexPath.row];
if (_delegate)
{
[_delegate selectedPlayer:selectedPlayer];
}
}
So the images wont set for all of the players at once, but they also do not clear after another player is selected.
How do I get the colors to change without writing 240 if and else if statements? and how would I get the colors to clear when I select another player?
Assuming you have all the 50 images and you know which challenge corresponds to which image I would put the status image on top of the actual challenge image:
- (void)setChallengesDone:(NSArray*)doneAr next:(NSArray*)nextAr current:(NSArray*)currentAr andPass:(NSArray*)passAr
{
// remove additions from the previous selected player
UIView *prevAdditionsView = [self.view viewWithTag:122333];
while (prevAdditionsView != nil)
{
[prevAdditionsView removeFromSuperview];
prevAdditionsView = [self.view viewWithTag:122333];
}
for (int i=0; i<[doneAr count]; i++)
{
[self addChallengeImageAdditionWithImage:#"status_done" forChallenge:[doneAr objectAtIndex:i]];
}
for (int i=0; i<[nextAr count]; i++)
{
[self addChallengeImageAdditionWithImage:#"status_next" forChallenge:[nextAr objectAtIndex:i]];
}
for (int i=0; i<[currentAr count]; i++)
{
[self addChallengeImageAdditionWithImage:#"status_current" forChallenge:[currentAr objectAtIndex:i]];
}
for (int i=0; i<[passAr count]; i++)
{
[self addChallengeImageAdditionWithImage:#"status_free" forChallenge:[passAr objectAtIndex:i]];
}
}
- (void)addChallengeImageAdditionWithImage:(NSString*)image forChallenge:(NSString*)challengeTitle
{
UIImageView *challengeImage = [challenges objectForKey:challengeTitle];
CGRect frame = challengeImage.frame;
UIImageView *statusImg = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:image]] autorelease];
[statusImg setFrame:frame];
[statusImg setAlpha:0.5]; // optionally add some transparency
[statusImg setTag:122333];
[self.view addSubview:statusImg];
[self.view bringSubviewToFront:challengeImage]; // bring challenge image to front
}
The simplest way to map your challenge titles with the UIImageViews is to maintain a NSDictionary with the challenge titles as keys, and a references to their corresponding UIImageViews as values.
This is an excellent example of the model/view concept.
Each challenge is a model with all the info required (challenge name, status, timestamp and others).
Each of your 50 views is a "challenge view" that knows how to render any challenge.
The status data is in the model; the status image is in the view.
Example:
-(void) drawChallenge: (Challenge*) challenge
{
// Draw challenge name as text
switch ([challenge status])
{
case done: // draw "done" image
case next: // draw "next" image
}
}
The idea is that the challenge itself should not know about how it is rendered, and the view should not know about what the challenge contains. The view is responsible for drawing it.
This could be packed into a ChallengeView subclass of UIView. Then, create your 50 or so ChallengeViews, and call [currentView drawChallenge: currentChallenge].
Essentially, when a new challenge is added, you create a view for it, and give the view a pointer to the challenge. When the challenge view is rendered by iOS, it'll draw "its" challenge as you have described in the drawChallenge method.
If you need a primer on the Model-View-Controller pattern, this section of the Apple docs is pretty good. You can disregard the Controller role in this situation.
Related
I have constructed the following method fetchLastFiveLogins and the method successfully adds the users avatar to the _avatarButton. However, when a user taps the avatar it calls the fillUserName method. That part is working, but I can't figure out how to fill the _textfieldUsername with the username associated with the avatar. Below is a snippet of the fetchLastFiveLogins method.
// sort / filter "results" to display the last five "lastLogin(s)"
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"lastLogin" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[request setFetchLimit:5];
[request setSortDescriptors:sortDescriptors];
// fetch records and handle error
NSError *error;
NSArray *results = [_managedObjectContext executeFetchRequest:request error:&error];
if (!results) {
// handle error
// also if there is login data handle error so app doesn't crash
}
Account *anAccount;
// create a stock image
UIImage *btnImage = [UIImage imageNamed:#"HomeBrewPoster1.jpg"];
NSMutableArray *avatars = [NSMutableArray arrayWithCapacity:5];
for ( anAccount in results) {
NSLog(#"results%#",anAccount.lastLogin);
if(anAccount.lastLogin) {
NSLog(#"anAccount.lastLogin = %#, by:%#",anAccount.lastLogin,anAccount.username);
if (anAccount.avatar != nil) {
UIImage *avatarImg = [UIImage imageWithData:anAccount.avatar ];
[avatars addObject:avatarImg];
}
else {
[avatars addObject:btnImage];
}
}
}
NSLog(#"avatars array%lu",(unsigned long)avatars.count);
for ( NSInteger i = 0; i < 4; i++) {
// Check that we have enough logins
if (i < results.count) {
NSLog(#"avatars =%#",avatars[i]);
CGFloat staticX = 0;
CGFloat staticWidth = 80;
CGFloat staticHeight = 80;
CGFloat staticPadding = 5;
_avatarButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// the last two values control the size of the button
_avatarButton.frame = CGRectMake(0, 0, 80, 80);
[_avatarButton setFrame:CGRectMake((staticX + (i * (staticHeight + staticPadding))),5,staticWidth,staticHeight)];
// make corners round
_avatarButton.layer.cornerRadius = 40; // value varies -- // 35 yields a pretty good circle.
_avatarButton.clipsToBounds = YES;
// assign method / action to button
[_avatarButton addTarget:self action:#selector(fillUserName) forControlEvents:UIControlEventTouchDown];
[_avatarButton setBackgroundImage:[avatars objectAtIndex:i] forState:UIControlStateNormal];
NSLog(#"avatarImage = %#",[_avatarButton backgroundImageForState:UIControlStateNormal]);
[_avatarScroll addSubview:_avatarButton];
}
}
}
Step 1: Make the fillUserName method take the parameter fillUserName:(id) sender, so that the method will be passed the button that was pressed. You'll want to tweak the addTarget so that it uses #selector(fillUserName:) (with the colon at the end).
Step 2: You'll need to be able to distinguish which of the buttons was pressed. Often people use the tag property of UIButton (and other controls) to distinguish the buttons. If you set the tag to be the array index of the result, then the button with tag 0 is the 0th entry in your results array. See this question: How do i set and get UIButtons' tag? for some code samples.
Step 3: Ensure that you've held on to references to the results array, so that you can access it from the fillUserName: method.
Update: As I mention in my comment, below, a solution that makes use of blocks seems like a much better solution, and some folks have written some nice code to enable that.
I'm working on an iPhone game and currently the game uses many UIImageViews to show space ships, bullets and other things. The game probably has 30-40 different subviews in the view controller and I've decided that I should probably programmatically add subviews when they are needed rather than starting the game with them in the hidden state and making them unhidden when needed (for performance issues) so here are my questions:
(1) will there be a significant performance gain from adding subviews when needed?
(2) how do I release a subview when ARC is enabled? Im trying to add the views (based on type) into an NSMutableArray when its created to hold it, and removing it from the array when I'm done using it, does removing it from the array deallocate that memory?
heres the code (theres an NSTimer that runs the movement method every 0.03 seconds, and the get and set methods are on an "instance variable" NSMutableArray);
-(void)movement {
if (shootButton3.isHighlighted) {
NSMutableArray *array = [self getBulletArray];
[self setarray:array];
}
[self shootBullet: [self getArray]];
}
-(NSMutableArray *)getBulletArray {
UIImageView *bullet = [[UIImageView alloc] initWithFrame:CGRectMake(ship.center.x + 20, ship.center.y, 15, 3)];
bullet.image = [UIImage imageNamed:#"bullet2.png"];
bullet.hidden = NO;
[self.view addSubview:bullet];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:bullet];
return array;
}
-(void)shootBullet: (NSMutableArray *)bulletArray {
for (int i = 0; i < [bulletArray count]; i++) {
UIImageView *bullet = [bulletArray firstObject];
bullet.center = CGPointMake(bullet.center.x + 4, bullet.center.y);
if (bullet.center.x > 500) {
bullet.hidden = YES;
[bulletArray removeObjectAtIndex:0];
}
}
}
-(void)setarray:(NSMutableArray *) array {
bulletArray = array;
}
-(NSMutableArray *)getArray {
return bulletArray;
}
To answer your two questions:
Question 1: Yes, there will be a performance increase for sure, regardless of how large the UIImageViews are.
Question 2: Simply set the imageView to nil: self.imageView = nil;
I guess I'm missing something obvious, but I simply can't figure out how to obtain the label of a CCMenuItemFont.
Background
I'm building a simple hangman game for the iPad. For entering the next guess, I've added 26 buttons to the UI (one for each letter of the alphabet) and wired them all to the same event handler.
Now, inside the event handler, I'd like to obtain the label of the button to update the current guess, but CCMenuItemFont apparently doesn't respond to text or label.
Problem
So - what method can I use to obtain the label of a CCMenuItem?
Code
Code for creating the buttons:
-(void)addButtons {
NSArray* charArray = [NSArray arrayWithObjects:
#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",
#"L",#"M",#"N",#"O",#"P",#"Q",#"R",
#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
[CCMenuItemFont setFontName:#"Marker Felt"];
[CCMenuItemFont setFontSize:45];
NSMutableArray* buttonArray = [NSMutableArray array];
for (unsigned int i=0; i < [charArray count]; ++i) {
CCMenuItemLabel* buttonMenuItem = [CCMenuItemFont
itemWithString:(NSString*)[charArray objectAtIndex:i]
target:self selector:#selector(buttonTapped:)];
buttonMenuItem.color = ccBLACK;
buttonMenuItem.position = ccp(60 + (i/13)*40, 600 - (i%13)*40);
[buttonArray addObject:buttonMenuItem];
}
CCMenu *buttonMenu = [CCMenu menuWithArray:buttonArray];
buttonMenu.position = CGPointZero;
[self addChild:buttonMenu];
}
And the event handler:
- (void)buttonTapped:(id)sender {
// Get a reference to the button that was tapped
CCMenuItemFont *button = (CCMenuItemFont *)sender;
[_guess addObject:[button text]]; // this throws an exception because text is the wrong method
[self paintCurrentGuess];
}
You're adding to your menu a CCMenuItemLabel, not a CCMenuItemFont (which actually extends the first one). In both cases, you need to access to the inner label containing the text.-
CCMenuItemLabel *button = (CCMenuItemLabel *)sender;
NSString *label = button.label.string;
Based on some earlier questions (ex: ios5 how to pass prepareForSegue: a UIImageView) I was wondering how smooth this technique is, say when doing a modal segue with animated = NO.
I can toss together a test but I imagine someone has already scoped out the performance and practical pitfalls of using this as a transition technique. I would be interested in hearing any details - for example, does the UIImageView animation restart or does it continue apace?
If you pass an animating image view to another controller, it looks like the animation continues apace. I can't see any "hitch" in the animation. Going forward with a modal presentation worked fine. I couldn't go back to the first controller, by just dismissing, I had to add the image view back to the view to make that work, and even then it only worked if I turned off auto layout (otherwise I get an error saying it can't install a constraint). So, to go back and forth with modals (with no animation) I had this in the first controller:
- (void)viewDidLoad {
[super viewDidLoad];
self.isFirst = YES;
NSMutableArray *imgArray = [NSMutableArray array];
for (int i = 1; i< 41; i++) {
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:#"New_PICT%04d.jpg",i]];
if (img) {
[imgArray addObject:img];
}
}
self.iv.animationImages = imgArray;
self.iv.animationDuration = 10;
[self.iv startAnimating];
}
-(void)viewDidAppear:(BOOL)animated {
if (self.isFirst) {
self.isFirst = NO;
}else{
self.iv.frame = CGRectMake(48, 48, 48, 48);
[self.view addSubview:self.iv];
}
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
SecondViewController *sec = segue.destinationViewController;
sec.iv = self.iv;
}
Hi I am trying to save data into core data and having some trouble... I have a Team Entity and a Player Entity The Team Entity is set up as a one to many relationship with the Player Entity... on my "NewTeamViewController" there are two sections, in the second section is where you add players to the team. In the section header there is a button to add a new player... When that button is pressed a new cell appears with three textFields, each with default text in them (not placeholder text) then I am adding the new player to a MutableSet that will be added as the teams players. The tableview is using a custom cell (which is where the three textFields live)
The team saves correctly, except I am unable to save the data from the three text fields in the player cell. It just saves the default text in the cell for the player.
I am not sure how or where to give the data from the newly added cell to the newly added player object.
Here is some code...
-(void)saveButtonWasPressed {
self.team =[NSEntityDescription insertNewObjectForEntityForName:#"Team" inManagedObjectContext:self.managedObjectContext];
team.schoolName = _schoolName.text;
team.teamName = _teamName.text;
team.season = _season.text;
team.headCoach = _headCoach.text;
team.astCoach = _assistantCoach.text;
player.firstName = cell.playerFirstName.text;
player.lastName = cell.playerLastName.text;
player.number = cell.playerNumber.text;
[self.team addPlayers:_tempSet];
[self.managedObjectContext save:nil];
[self.navigationController popViewControllerAnimated:YES];
}
//////////////////////////////////////////////////////////////////////////////////////////////////
-(void)addPlayerButton {
player = (Player *)[NSEntityDescription insertNewObjectForEntityForName:#"Player"
inManagedObjectContext:self.managedObjectContext];
[_tempSet addObject:player];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
}
Add your NewTeamViewController as a target for the control event UIControlEventEditingChanged for each of your text fields. You can do this in code (cellForRowAtIndexPath...) or in your nib or storyboard. I would use a different action method for each of the three different text fields in each cell. Here is what your action methods might look like:
// Helper method
- (Player *)playerForTextField:(UITextField *)textField
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:textField.superview];
return [_tempArray objectAtIndex:indexPath.row];
}
- (IBAction)firstNameDidChange:(UITextField *)textField
{
Player *player = [self playerForTextField:textField];
player.firstName = textField.text;
}
- (IBAction)lastNameDidChange:(UITextField *)textField
{
Player *player = [self playerForTextField:textField];
player.lastName = textField.text;
}
- (IBAction)numberDidChange:(UITextField *)textField
{
Player *player = [self playerForTextField:textField];
player.number = textField.text;
}
Also, change your _tempSet to a _tempArray because knowing the order of the players in the table is useful.