Xcode and tag searching - ios

A simple inquiry.
When using Objective-C / Swift and one decides to implement tags for objects within the storyboard, how does the system search for the tags?
Does it approach this as a linear search? Therefore, implying that tags with a lower number value will be faster to search for? Or does it approach this entirely differently?
For example:
UIImageView *imageView = (UIImageView *)[self viewWithTag:1];
imageView.image = [UIImage imageNamed: #"Elderberries"];
vs
UIImageView *imageView = (UIImageView *)[self viewWithTag:100000000];
imageView.image = [UIImage imageNamed: #"Motherless_Goat"];
Thanks

I did some experiment, below is the code
//adding 30000 tag at first position
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
label.text = [NSString stringWithFormat:#"%d", 30000];
label.tag = 30000;
[self.view addSubview:label];
for (int i = 0; i < 30000; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
label.text = [NSString stringWithFormat:#"%d", i];
label.tag = i;
[self.view addSubview:label];
}
NSTimeInterval currentTime, fetchTime;
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label1 = (UILabel *)[self.view viewWithTag:5];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label1.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label2 = (UILabel *)[self.view viewWithTag:100];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label2.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label3 = (UILabel *)[self.view viewWithTag:1000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label3.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label4 = (UILabel *)[self.view viewWithTag:5000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label4.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label5 = (UILabel *)[self.view viewWithTag:10000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label5.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label6 = (UILabel *)[self.view viewWithTag:30000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label6.text, fetchTime - currentTime);
And below were the logs (reformatted so that comparison is easy)
Label:5 = 0.000011
Label:100 = 0.000043
Label:1000 = 0.000346
Label:5000 = 0.001169
Label:10000 = 0.002115
Label:30000 = 0.000009
Conclusion:
The viewWithTag: will take more time for higher tags (only if there are large number of objects), it might be possible that search is linear which I think is the case because view.subViews gives you the array in the order they are added not by the tag. Yes it takes more time and it almost work as linear search.
The time depends upon the index at which subview was added, in the above case time for 30000 tag is minimum than all other tags because it was added at first index.
The posible implementation of viewWithTag: could be like this
- (UIView *)viewWithTag:(NSInteger)tag {
for (UIView *view in self.subviews) {
if (view.tag == tag) {
return view;
}
}
return nil;
}

Related

selector for multiple uibuttons in uitableviewcell

I'm adding the same selector for multiple UIButtons which are part of a UITableViewCell and it works only for the first one. Am I missing something?
Here's my code:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *d = [tableData objectAtIndex:indexPath.row];
NSArray *answers = [d objectForKey:#"answers"];//array of { id = 35; text = "\U03c4\U03a\U03c0\U03bf\U03c4\U03b1"; }
UILabel *startDate = (UILabel *)[cell viewWithTag:100];
long long startDateEpoch = [[d objectForKey:#"startDate"] longLongValue];
NSDate *sDate = [NSDate dateWithTimeIntervalSince1970:startDateEpoch/1000];
NSDateFormatter *startDateFormatter = [[NSDateFormatter alloc] init];
[startDateFormatter setDateFormat:#"dd/MM/yyyy"];
startDate.text = [startDateFormatter stringFromDate:sDate];
((UILabel *)[cell viewWithTag:101]).text = [d objectForKey:#"subject"];
NSArray *tags = [d objectForKey:#"tags"];
((UILabel *)[cell viewWithTag:102]).text = [tags componentsJoinedByString:#" "];
NSString *imageURL = [d objectForKey:#"media"];
UIImageView *iv = (UIImageView *)[cell viewWithTag:103];
iv.contentMode = UIViewContentModeScaleAspectFit;
[iv sd_setImageWithURL:[NSURL URLWithString:imageURL]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
UIView *buttonsContainer = (UIView *)[cell viewWithTag:104];
for(UIView *vv in buttonsContainer.subviews){
[vv removeFromSuperview];
}
int index = 0;
NSLog(#"buttonsContainer children: %d", buttonsContainer.subviews.count);
for(NSDictionary *answer in answers){
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, index * 40 + (index+1)*5, [UIScreen mainScreen].bounds.size.width, 40)];
v.backgroundColor = [UIColor whiteColor];
CGRect labelFrame = v.frame;
labelFrame.origin.y = 0;
UILabel *l = [[UILabel alloc] initWithFrame:labelFrame];
l.text = (NSString *)[answer objectForKey:#"text"];
l.textAlignment = NSTextAlignmentCenter;
UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, v.frame.size.height - 1, v.frame.size.width, 1)];
bottomLine.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:205.0/255.0 blue:103.0/255.0 alpha:1.0];
UIButton *b = [[UIButton alloc] initWithFrame:v.frame];
[b addTarget:self action:#selector(answered:) forControlEvents:UIControlEventTouchUpInside];
[v addSubview:l];
[v addSubview:bottomLine];
[v addSubview:b];
[buttonsContainer addSubview:v];
index++;
}
}
So for example if 4 buttons are added, the selector is called only when I click on the first one. When I click on the other three nothing happens.
EDIT:
adding the answered: code:
- (void)answered:(UIButton *)sender
{
NSLog(#"#answered");
}
ok, I found it. Many cudos to TomSwift since his point gave me the idea to place borders on all the views in order to debug their frames size and origin.
Notice that I give to my buttons the same frame as their superviews, which is wrong since they should not have the same origin. The buttons' origin should be 0,0 since they have the same frame size as their superviews.
lessons learn for noobs like me:
When a button does not work, place borders in order to make sure their frame is within the superview's bounds.
Do not assign the same frame on a view and its subview. It will place it outside of the superview's bounds which in 92% of the cases brings undesirable behaviour.

UITableViewCell Duplicate Behavior With UIButton SetTitle And Cell Reuse?

I'm getting some really unusual behavior with my application. I have a tableview that loads cells based on data from a server, The data coming from the server is great, no duplicates and is how it should be. However as I scroll through my table I'm noticing UIButtons that I use setTitle on are showing duplicate title that were previously shown while scrolling, as if the reused cells aren't updating the title in some cases when setTitle is called..
UITableViewCell *cell = [self dequeueReusableCellWithIdentifier:DETAILED_TAGS_FEED_CELL_IDENTIFIER];
NSDictionary *tag = [self.tags objectAtIndex:indexPath.row];
ArgumentButton *nameButton = (ArgumentButton *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_NAME];
[nameButton addTarget:self action:#selector(tagSelected:) forControlEvents:UIControlEventTouchUpInside];
[nameButton setTitle:[NSString stringWithFormat:#"#%#", [tag objectForKey:#"tag"]] forState:UIControlStateNormal];
nameButton.argument = [tag objectForKey:#"tag"];
UILabel *totalFollowersLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_TOTAL_FOLLOWERS];
totalFollowersLabel.text = [tag objectForKey:#"followers"];
UILabel *followersLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_FOLLOWERS];
UIView *dividerView = (UIView *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_DIVIDER];
UILabel *totalProductsLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_TOTAL_PRODUCTS];
totalProductsLabel.text = [tag objectForKey:#"products"];
UILabel *productsLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_PRODUCTS];
if (self.allowFollow) {
totalFollowersLabel.frame = CGRectMake(30, totalFollowersLabel.frame.origin.y, totalFollowersLabel.frame.size.width, totalFollowersLabel.frame.size.height);
followersLabel.frame = CGRectMake(30, followersLabel.frame.origin.y, followersLabel.frame.size.width, followersLabel.frame.size.height);
dividerView.frame = CGRectMake(133, dividerView.frame.origin.y, dividerView.frame.size.width, dividerView.frame.size.height);
totalProductsLabel.frame = CGRectMake(157, totalProductsLabel.frame.origin.y, totalProductsLabel.frame.size.width, totalProductsLabel.frame.size.height);
productsLabel.frame = CGRectMake(157, productsLabel.frame.origin.y, productsLabel.frame.size.width, productsLabel.frame.size.height);
NSString *followButtonTitle = ([[tag objectForKey:#"followed"] isEqualToString:#"1"]) ? #"Unfollow" : #"Follow";
ArgumentButton *followButton = (ArgumentButton *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_FOLLOW];
followButton.argument = indexPath;
[followButton addTarget:self action:#selector(followSelected:) forControlEvents:UIControlEventTouchUpInside];
[followButton setTitle:followButtonTitle forState:UIControlStateNormal];
followButton.hidden = NO;
}
HorizontalScroll *scroll = (HorizontalScroll *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_SCROLL];
scroll.contentOffset = CGPointMake(-5, 0);
scroll.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
scroll.pagingEnabled = NO;
[scroll resetItems];
NSArray *items = [tag objectForKey:#"items"];
NSMutableArray *scrollItems = [[NSMutableArray alloc] init];
for (NSDictionary *item in items) {
NSArray *scrollItemXIB = [[NSBundle mainBundle] loadNibNamed:#"DetailedFeedScrollItemView" owner:self options:nil];
UIView *scrollItemView = [scrollItemXIB lastObject];
ArgumentButton *itemButton = (ArgumentButton *)[scrollItemView viewWithTag:DETAILED_FEED_SCROLL_ITEM_TAG_BUTTON];
[itemButton sd_setImageWithURL:[APIController resourceUrlForUserId:[item objectForKey:#"userId"] resourceName:[item objectForKey:#"thumbnail"]] forState:UIControlStateNormal];
[itemButton addTarget:self action:#selector(productSelected:) forControlEvents:UIControlEventTouchUpInside];
itemButton.argument = [item objectForKey:#"id"];
[scrollItems addObject:scrollItemView];
}
[scroll loadItems:scrollItems];
return cell;
Note: I am using UITableViewCells within their own XIB for this, which is set like this in viewDidLoad.
[self registerNib:[UINib nibWithNibName:#"DetailedTagsFeedTableViewCell" bundle:nil] forCellReuseIdentifier:DETAILED_TAGS_FEED_CELL_IDENTIFIER];
It's as if [nameButton setTitle:] is not setting the right titles while scrolling? I've tried a little debugging by setting the followersLabel text equal to the same value that we're attempting to set with setTitle on the nameButton, and the value IS correct when setting the .text property of the label in the same cell.. Very confusing.
The Argument button class is nothing special. Just a simple subclass that has a public property for passing an argument with itself to a target/action.

Adding a tag to UIImageView

I have an array of an object (which contains an image and some text) and when I iterate around the array and add the image to a UIImageView (which is then added to a UIScrollView) all works well and each image is added with a specific UIImageView to the UIScrollView.
However as soon as I add a tag to the UIImageView not all the images are rendered within the added UIImageView (which is in the UIScrollView (some are missing, some are visible).
If I remove the tag, all works well? Is there something with tags I'm not grasping? Any help much appreciated.
for (Article *al in articleLists){
CGRect frame;
frame.origin.x = self.FeaturedView.frame.size.width * counter;
frame.origin.y = 0;
frame.size = self.FeaturedView.frame.size;
CGRect frameTextArea;
frameTextArea.origin.x = self.FeaturedView.frame.size.width * counter;
frameTextArea.origin.y = (self.FeaturedView.frame.size.height / 2) + 10;
frameTextArea.size.width = self.FeaturedView.frame.size.width;
frameTextArea.size.height = (self.FeaturedView.frame.size.height / 2) - 20;
CGRect frameTextLabel;
frameTextLabel.origin.x = (self.FeaturedView.frame.size.width * counter) + 20;
frameTextLabel.origin.y = (self.FeaturedView.frame.size.height / 2) + 10;
frameTextLabel.size.width = self.FeaturedView.frame.size.width - 40;
frameTextLabel.size.height = (self.FeaturedView.frame.size.height / 2) - 20;
if (al.imageURL != NULL){
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.contentMode = UIViewContentModeScaleAspectFill;
//imageView.tag = counter;
imageView.image = al.imageArticle;
UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapGestureCaptured:)];
[imageView addGestureRecognizer:imageTap];
imageView.userInteractionEnabled = YES;
UIView *viewTextArea = [[UIView alloc]initWithFrame:frameTextArea];
viewTextArea.backgroundColor = [UIColor blackColor];
viewTextArea.alpha = 0.9;
UILabel *textLabel = [[UILabel alloc] initWithFrame:frameTextLabel];
textLabel.textColor = [UIColor whiteColor];
textLabel.backgroundColor = [UIColor clearColor];
textLabel.numberOfLines = 2;
textLabel.font = [UIFont fontWithName:#"Droid Sans" size:18];
textLabel.text = [al.currentTitle uppercaseString];
[self.FeaturedView addSubview:imageView];
[self.FeaturedView addSubview:viewTextArea];
[self.FeaturedView addSubview:textLabel];
}
else{
//UIImage *image = [UIImage imageNamed:#"ArticlePlaceholder.png"];
}
counter++;
}

I want my UILabel to follow my UISlider value

I follow the code of user2207904
on viewDidLoad I create 20 sliders and 20 labels
then my 20 labels take the values of my faders (label.text= [NSString stringWithFormat:#"%i", slvalue];)
but like this if I move my labels don't follows my faders values...
how can I do to my labels follows my faders values?
MY CODE
- (void)viewDidLoad
{
[super viewDidLoad];
for(int i=0; i< 20; i++){
//sliders
UISlider *slider = [[[UISlider alloc] initWithFrame:CGRectMake(1+i*50, 450, 300, 10)] autorelease];
slider.minimumValue = 1;
slider.maximumValue = 100;
slider.continuous = YES;
[self.view addSubview:slider];
slider.transform = CGAffineTransformRotate(slider.transform, 270.0/180*M_PI);
[slider setThumbImage:thumbImage0 forState:UIControlStateNormal];
[slider release];
// label
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(1+i*50, 640, 40, 15)];
int slvalue = slider.value;
label.text= [NSString stringWithFormat:#"%i", slvalue];
[self.view addSubview:label];
[label release];
}
New issue :
mofified
I do this :
i put an IBAction in my FirstViewController.m
- (IBAction)sliderUpdate:(UISlider *)sender {
self.label.text = [NSString stringWithFormat:#"%g", sender.value];
}
and put this in my viewDidLoad (FirstViewController.m)
{
[super viewDidLoad];
for(int i=0; i< 20; i++){
//sliders
UISlider *slider = [[[UISlider alloc] initWithFrame:CGRectMake(1+i*50, 450, 300, 10)] autorelease];
slider.minimumValue = 1;
slider.maximumValue = 100;
slider.continuous = YES;
[slider addTarget:self action:#selector(sliderUpdate:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:slider];
slider.transform = CGAffineTransformRotate(slider.transform, 270.0/180*M_PI);
[slider setThumbImage:thumbImage0 forState:UIControlStateNormal];
[slider release];
// label
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(1+i*50, 640, 40, 15)];
int slvalue = slider.value;
label.text= [NSString stringWithFormat:#"%i", slvalue];
[self.view addSubview:label];
[label release];
}
i have this error in my (IBAction)sliderUpdate: Property 'label' not found on object of type 'FirstViewController *'
If you control drag from a slider to the implementation of your UIViewController, it will set up an IBAction method that is called whenever the value is changed. In this method, simply set the text of your label. No need to make a special subclass.
The code will end up looking something like this:
- (IBAction)setLabel:(UISlider *)sender {
self.myLabel.text = [NSString stringWithFormat:#"%g", sender.value];
}
EDIT: It sounds like you are making the sliders programmatically. In that case, you're going to have to call addTarget:action:forControlEvents: on each one to set up the target-action. (The control event will be UIControlEventValueChanged.)
Also, as far as knowing what slider goes to what label, you could make 2 NSArrays in which the ith slider in one array matches the ith label in the other array.
Drag and drop or programetically create one UILabel and UISlider ,then in the Slider use this for slider action
-(IBAction)slider:(id)sender {
NSString *s=[NSString stringWithFormat:#"%f",slider.value];
[label setText:s]; }
So whenever you change your slider your label value also changes.I hope you got it ryt?

UItableviewcell glitch

So sometimes upon returning to my main menu for my game I am greeted by something quite extraordinary. As you can see from the picture I have replicated cells outside the UIView Table. Now at first I thought it was a graphics corruption that was based on memory issues, Then I discovered you could interact with them, they are valid cells...not ghost images and they respond to code, So I then did a little search and though that my table was stuck in editing mode or something so I call setediting:NO everywhere I could. And it haunts me still.
Does anyone even have the first idea what could be causing this? It does not happen all the time but it only ever seems to happen...IF it does when I am popping back to this screen from another view on top of it. I also can't replicate it consistently so it's hard to fix and know what is causing it.
Please keep in mind I might be doing something or not doing something I have not mentioned so don't forget to ask everything you may think relevant and I will be happy to inform you.
EDIT:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[CurrentGamesInfo sharedCurrentGamesInfo] _currentGames] count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_indexPath = indexPath;
NSLog(#"%i",_indexPath.row);
[_indexPath retain];
[[CurrentGamesInfo sharedCurrentGamesInfo] SetCurrentGameWithIndex:[_indexPath row]];
UIView *tempView = [[[tableView cellForRowAtIndexPath:indexPath] contentView] viewWithTag:200];
if([[[(UIButton*)[tempView viewWithTag:CELL_BUTTONTEXT_ID] titleLabel] text] isEqualToString:#"Waiting"])
{
return;
}
if( ![[CurrentGamesInfo sharedCurrentGamesInfo] _selectedGame].isGameReady )
{
[_PopUp OptionsMessage:#"Game Not Ready" withTitle:#"Hold Your Horsies" hideBackButton:YES];
return;
}
NSString *gameID = [[[CurrentGamesInfo sharedCurrentGamesInfo] _selectedGame] GetGameID];
NSLog(#"%i",[[[CurrentGamesInfo sharedCurrentGamesInfo] _selectedGame] GetTurnNumber].intValue);
NSData *pngData = [NSData dataWithContentsOfFile:[AppDelegate applicationDocumentDirectory:gameID]];
UIImage *image = [UIImage imageWithData:pngData];
PhotoImage *photoImg = [[PhotoImage alloc]init];
[photoImg set_imageToSend:image];
[[[CurrentGamesInfo sharedCurrentGamesInfo] _selectedGame] SetImageToSend:photoImg];
[photoImg release];
UIImageView * imgView = (UIImageView*)[[[[tableView cellForRowAtIndexPath:indexPath] contentView]viewWithTag:300] viewWithTag:301];
[[[CurrentGamesInfo sharedCurrentGamesInfo]_selectedGame]setOpponentProfilePic:imgView.image];
[self TempCurrentGameFunction];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
WARNING: HEFTY FUNCTION INCOMING
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
GameInfo *gameThisRow = [[[CurrentGamesInfo sharedCurrentGamesInfo]_currentGames] objectAtIndex:indexPath.row];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
NSLog(#"row : %i",indexPath.row);
NSLog(#"current game count : %i",[[[CurrentGamesInfo sharedCurrentGamesInfo] _currentGames]count]);
NSString *gameType = #"";
UIButton *gameStatusButton = [[UIButton alloc]initWithFrame:CGRectMake(100, -5, 90, 70)];
Boolean isYourTurn = [[gameThisRow GetPlayerRole] intValue] ? YES : NO;
NSString *gameStateString = #"Your Move";
[cell setUserInteractionEnabled:YES];
[cell setTag:ACTIVE_GAME_CELL];
if(!isYourTurn)
{
//_activeGameCount--;
gameStateString = #"Waiting";
[cell setUserInteractionEnabled:NO];
[cell setTag:INACTIVE_GAME_CELL];
}
[gameStatusButton setTitle:gameStateString forState:UIControlStateNormal];
[[gameStatusButton titleLabel] setFont:[UIFont fontWithName:#"Fredoka One" size:10]];
[gameStatusButton setTag:CELL_BUTTONTEXT_ID];
if( indexPath.row < [[[CurrentGamesInfo sharedCurrentGamesInfo] _currentGames]count])
{
switch ([gameThisRow gameType])
{
case 0:
gameType = #"Open Game";
[gameStatusButton setBackgroundImage:[UIImage imageNamed:#"buttonB_blue.png"] forState:UIControlStateNormal];
break;
case 1:
{
gameType = #"Challenge Game";
[gameStatusButton setBackgroundImage:[UIImage imageNamed:#"buttonB_orange.png"] forState:UIControlStateNormal];
}
break;
case 2:
{
gameType = #"Battle Game";
[gameStatusButton setBackgroundImage:[UIImage imageNamed:#"buttonB_pink.png"] forState:UIControlStateNormal];
}
break;
default:
break;
}
}
NSLog(#"%#",[[gameThisRow GetFaceBookData]objectForKey:#"name"]);
NSString *name = [[gameThisRow GetFaceBookData]objectForKey:#"name"];
UIView *labelView = [[UIView alloc] initWithFrame:CGRectMake(80, 10, 100, 50)];
[labelView setTag:200];
[labelView addSubview:gameStatusButton];
[gameStatusButton release];
[labelView setBackgroundColor:[UIColor clearColor]];
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 100, 20)];
NSString *text = name;
NSArray *nameArray = [text componentsSeparatedByString:#" "];
NSString *nameWithInitials;
nameWithInitials = [NSString stringWithFormat:#"%#",[nameArray objectAtIndex:0]];
for( int i = 1; i < nameArray.count; ++i )
{
NSString *temp = [nameArray objectAtIndex:i];
nameWithInitials = [nameWithInitials stringByAppendingFormat:#" %C.",[temp characterAtIndex:0]];
}
text = nameWithInitials;
int maxSize = 20;
int minSize = 8;
UIFont *font = [UIFont fontWithName:#"Fredoka One"size:maxSize];
/* Time to calculate the needed font size.
This for loop starts at the largest font size, and decreases by two point sizes (i=i-2)
Until it either hits a size that will fit or hits the minimum size we want to allow (i > 10) */
for(int i = maxSize; i > minSize; i=i-2)
{
// Set the new font size.
font = [font fontWithSize:i];
// You can log the size you're trying: NSLog(#"Trying size: %u", i);
/* This step is important: We make a constraint box
using only the fixed WIDTH of the UILabel. The height will
be checked later. */
CGSize constraintSize = CGSizeMake([labelName frame].size.width, MAXFLOAT);
// This step checks how tall the label would be with the desired font.
CGSize labelSize = [text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
/* Here is where you use the height requirement!
Set the value in the if statement to the height of your UILabel
If the label fits into your required height, it will break the loop
and use that font size. */
if(labelSize.height <= [labelName bounds].size.height)
break;
}
// You can see what size the function is using by outputting: NSLog(#"Best size is: %u", i);
// Set the UILabel's font to the newly adjusted font.
[labelName setFont:font];
// Put the text into the UILabel outlet variable.
[labelName setText:text];
[labelName setTextColor:[UIColor grayColor]];
[labelName setBackgroundColor:[UIColor clearColor]];
[labelName setTextAlignment:UITextAlignmentCenter];
[labelView addSubview:labelName];
[labelName release];
UILabel *labelSubtitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 50)];
[labelSubtitle setText:gameType];
[labelSubtitle setFont:[UIFont fontWithName:#"Fredoka One" size:10]];
[labelSubtitle setTextColor:[UIColor grayColor]];
[labelSubtitle setBackgroundColor:[UIColor clearColor]];
[labelSubtitle setTextAlignment:UITextAlignmentCenter];
[labelView addSubview:labelSubtitle];
[labelSubtitle release];
[[cell contentView] addSubview:labelView];
NSString *path = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture?width=200&height=200",[[gameThisRow GetFaceBookData]objectForKey:#"id"] ];
UIImageView *pictureImage = [[UIImageView alloc] init];
[pictureImage setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:#"Icon-Small.png"]success:^(UIImage *image)
{
pictureImage.image = [image imageScaledToSize:CGSizeMake(100, 100)];
} failure:^(NSError *error)
{
[pictureImage setImage:[[UIImage imageNamed:#"Icon-Small.png" ]imageScaledToSize:CGSizeMake(50, 50)]];
NSLog(#"%#",[error localizedDescription]);
}];
NSLog(#"%#",[pictureImage image]);
pictureImage.layer.masksToBounds = YES;
[pictureImage setFrame:CGRectMake(pictureImage.frame.origin.x+20, 37 - 25, 50, 50)];
UIImageView *pictureFrameView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"profile_frame.png"]];
CGRect temp = pictureImage.frame;
//hand & hard coded, i feel so ashamed and sullied
temp.origin.x -= 12;
temp.origin.y -= 9;
temp.size.width = 70;
temp.size.height = 73;
[pictureFrameView setFrame:temp];
UIView *pictureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
[pictureView addSubview:pictureFrameView];
[pictureView addSubview:pictureImage];
[pictureImage setTag:301];
[pictureFrameView release];
[pictureImage release];
[[cell contentView] addSubview:pictureView];
[pictureView setTag:300];
[pictureView release];
//custom stuff start
UIImage *rowBackground;
//UIImage *selectionBackground;
NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"table_bottom.png"];
//selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
rowBackground = [UIImage imageNamed:#"table_top.png"];
//selectionBackground = [UIImage imageNamed:#"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"table_bottom.png"];
//selectionBackground = [UIImage imageNamed:#"bottomRowSelected.png"];
}
else
{
rowBackground = [UIImage imageNamed:#"table_mid.png"];
//selectionBackground = [UIImage imageNamed:#"middleRowSelected.png"];
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:rowBackground];
[cell setBackgroundView:imageView];
[imageView release];
//((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
//custom stuff end
__block CGRect newPos = inviteFriendsParentView.frame;
CGRect tempCurrentGameSubMenuFrame = currentGameSubMenu.frame;
tempCurrentGameSubMenuFrame.size.height = [friendsTable rowHeight] * [friendsTable numberOfRowsInSection:0] + 10;
currentGameSubMenu.frame = tempCurrentGameSubMenuFrame;
float bottomofFrameYPos = currentGameSubMenu.frame.size.height;
newPos.origin.y += bottomofFrameYPos;
return cell;
}

Resources