bubble-message with avatar images and avatar name with time-stamps - iphone

I have to implement bubble messages with the senders AVATAR and Sender's name with time-stamps same as below screen shot.
I have successfully implemented the simple bubble type messaging. Right now I have some good Git-hub projects which provide me but what I need is something different.
I had even used acanichat but no luck.
so can anyone suggest me good tutorial for the same? or anyone have already done this with this Git-hub Library or with any other library?
I want a bubble-message with the senders AVATAR and Sender's name with time-stamps, please take a look at following image.
Your suggestion are appreciable.

Why not you create your own chat Table ? You just need to create Two custom Cells and With the help of XIB file you can give any Look you want.
Use Differentiators and conditions like Below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
CGSize boundingSize = CGSizeMake(messageWidth-20, 10000000);
CGSize itemTextSize = [messageText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:boundingSize
lineBreakMode:NSLineBreakByWordWrapping];
float textHeight = itemTextSize.height+7;
if (messageType isEqualToString:#"textByme"]) {
CustomCell1 *cell = (CustomCell1 *)[self.tableview dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell1" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
UIImageView *bubbleImage=[[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"chatbubble"] stretchableImageWithLeftCapWidth:15 topCapHeight:15]];
bubbleImage.tag=55;
[cell.contentView addSubview:bubbleImage];
[bubbleImage setFrame:CGRectMake(255-itemTextSize.width,5,itemTextSize.width+10,textHeight)];
UITextView *messageTextview=[[UITextView alloc]initWithFrame:CGRectMake(250-itemTextSize.width,0,itemTextSize.width+15, textHeight)];
[cell.contentView addSubview:messageTextview];
messageTextview.editable=NO;
messageTextview.text = messageText;
messageTextview.dataDetectorTypes=UIDataDetectorTypeAll;
messageTextview.textAlignment=NSTextAlignmentJustified;
messageTextview.font=[UIFont fontWithName:#"Helvetica Neue" size:13.0];
messageTextview.backgroundColor=[UIColor clearColor];
messageTextview.tag=indexPath.row;
cell.Avatar_Image.image=[UIImage imageNamed:#"avatar.png"];
cell.time_Label.text=data.messageTime;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
messageTextview.scrollEnabled=NO;
return cell;
}
else{
CustomCell2 *cell = (CustomCell2 *)[self.tableview dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell2" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
UIImageView *bubbleImage=[[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"chatbubble"] stretchableImageWithLeftCapWidth:15 topCapHeight:15]];
[cell.contentView addSubview:bubbleImage];
[bubbleImage setFrame:CGRectMake(50,5, itemTextSize.width+10, textHeight)];
bubbleImage.tag=56;
UITextView *messageTextview=[[UITextView alloc]initWithFrame:CGRectMake(50,0,itemTextSize.width+15, textHeight)];
[cell.contentView addSubview:messageTextview];
messageTextview.editable=NO;
messageTextview.text = messageText;
messageTextview.dataDetectorTypes=UIDataDetectorTypeAll;
messageTextview.textAlignment=NSTextAlignmentJustified;
messageTextview.backgroundColor=[UIColor clearColor];
messageTextview.font=[UIFont fontWithName:#"Helvetica Neue" size:13.0];
messageTextview.scrollEnabled=NO;
messageTextview.tag=indexPath.row;
cell.Avatar_Image.image=[UIImage imageNamed:#"avatar"];
cell.time_Label.text=feed_data.messageTime;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
return cell;
}
}
For Height:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float cellHeight;
// text
NSString *messageText = #"Your text";
//
CGSize boundingSize = CGSizeMake(messageWidth-20, 10000000);
CGSize itemTextSize = [messageText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:boundingSize
lineBreakMode:NSLineBreakByWordWrapping];
// plain text
cellHeight = itemTextSize.height;
if (cellHeight<25) {
cellHeight=25;
}
return cellHeight+30;
}

Related

UISwitch untoggling on scroll of a UITableView

I have a UITableView with a UISwitch as the accessoryView. My problem is that if I toggle one of the switches then scroll so the switch it out of view it returns to its previous state.
Please see video.
Does anyone know why this might be and how to solve it?
Here is the code that adds the switch view and deals with its action.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"POICell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier ];
//set the cell text to the
cell.textLabel.text = [self.catNames objectAtIndex:[indexPath row]];
NSString *toggle = [self.toggleArray objectAtIndex:[indexPath row]];
//add switch
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//create an instance of the database oject
DataBase * dataBase = [[DataBase alloc] init];
//open the database connection
[dataBase openDB];
NSString *imageName = [dataBase getPinImageNameFromCatID:[self.catIDs objectAtIndex:[indexPath row]]];
//get the root file path for the images
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/pinImages/%#",documentsDirectory, imageName];
//add image
NSURL *imageURL = [NSURL fileURLWithPath:filePath];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.imageView.image = image;
NSLog(#"%#",[self.catIDs objectAtIndex:[indexPath row]]);
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchView;
[switchView addTarget:self action:#selector(switchChanged: ) forControlEvents:UIControlEventValueChanged];
if ([toggle isEqualToString: #"OFF"]) {
[switchView setOn:NO animated:NO];
}else{
[switchView setOn:YES animated:NO];
}
return cell;
}
- (void) switchChanged:(id)sender {
//get the switch that it was sent from
UISwitch *switchInCell = (UISwitch *)sender;
//get the cell it was sent from
UITableViewCell * cell = (UITableViewCell *) switchInCell.superview;
//get the row it was sent from
NSIndexPath * indexpath = [self.inputTableView indexPathForCell:cell];
//cast the indexpath to int
NSInteger variable = indexpath.row;
//set the filter as off in the user defualts.
[self.filterDic setValue:switchInCell.on ? #"ON" : #"OFF" forKey:[self.catIDs objectAtIndex:variable]];
//store the newdic in the user defualts
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
//save the dic to user defaults
[prefs setObject:self.filterDic forKey:#"pinFilters"];
}
Thanks for any help.
There are two issues with your code (at least :)
Let me start with the one that is confusing you.
You set the status of each witch based on toggle. And the value of toggle is tanken from an array self.toggleArray.
Fine so far.
But when a value changes and the action switchChanged is called then you update self.filterDic but you do not update self.toggleView.
And this causes the problem:
Next time when a cell becomes visible cellForRowAtIndexPath is called again and will set the value based on toggle wich is based on self.toggleArray. And that still has the old values in it ... you see?
You are making this mistake probably because you have not yet fully understood the cell recycle mechanism. And that is probably what causes the second issue that I identified. Let me try to explain.
iOS or cocoa respectively tries to allocate as view cell objects as nessessary. That means that a cell wich scrolls off the creen is added to a pool from which it can be re-used the next time when a (similar) sell is required. So each time when there is a need for a new cell (one that becomes visible) cellForRowAtIndexPath is called. Wihin that you fetch a cell using dequeueReusableCellWithIdentifier. If there is a cell in that pool that was initialized with the same re-use identfier then that one (or one of those) is returned to the caller.
In recent iOS (respectively SDK versions) versions a new cell will be allocated and returned if none of these cells exists. (And that is why Murali's suggestion would not work perfectly either)
In older versions you had to check cell for nil and alloc/init a new on in those cases.
After that you freely allocate new subview objects regardless whether the cell was re-cycled and already has those subviews or not. Then you add and add and add the same subviews again and again.
How can you solve this? There are, as usual, several ways of dealing with that:
First - Check whether the cell was re-used or not. Just check if the Switch is already there or not. For doing that you could tag it with some value different from 0 and fetch the subview with this tag. If you dont't get it then the cell is new and you have to create all the additional subvies.
Second - You could always erase all subviews from the cell right after fetching the cell with dequeueReusableCellWithIdentifier. That is the easiest solultion because you do not have to change mutch to your existing code. It is not the most performant solution though.
Third - The most elegant solution is probably to subclass UITableViewCell every time when you want to add custom elements to a cell. In that case its init method would be called only once upon creation (and not upon re-usage) and there you can programmatically add all the custom subviews. You can, of course, design the cell and add all subviews in IB as you can with every UIView object. Witin cellForRowAtIndexPath you would only have to care for setting the appropriate values.
Perhaps your cells are being recycled.
Have a look at the accepted answer here:
iphone : uitableview : contents of a cell change on scrolling
Please use this method..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"POICell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UISwitch *switchView;
if (cell == nil)
{
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier ];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
switchView = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];//Change the frame
cell.accessoryView = switchView;
}
//set the cell text to the
cell.textLabel.text = [self.catNames objectAtIndex:[indexPath row]];
NSString *toggle = [self.toggleArray objectAtIndex:[indexPath row]];
//add switch
//create an instance of the database oject
DataBase * dataBase = [[DataBase alloc] init];
//open the database connection
[dataBase openDB];
NSString *imageName = [dataBase getPinImageNameFromCatID:[self.catIDs objectAtIndex:[indexPath row]]];
//get the root file path for the images
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/pinImages/%#",documentsDirectory, imageName];
//add image
NSURL *imageURL = [NSURL fileURLWithPath:filePath];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.imageView.image = image;
NSLog(#"%#",[self.catIDs objectAtIndex:[indexPath row]]);
[switchView addTarget:self action:#selector(switchChanged: ) forControlEvents:UIControlEventValueChanged];
if ([toggle isEqualToString: #"OFF"]) {
[switchView setOn:NO animated:NO];
}else{
[switchView setOn:YES animated:NO];
}
return cell;
}

How to Show UITableViewCellAccessoryCheckmark

I have a tableview which has a list of options the user has selcected( It is an edit page ).
the tableview looks as below
Apple UITableViewCellAccessoryCheckmark
Orange UITableViewCellAccessoryNone
Pineapple UITableViewCellAccessoryCheckmark Banana
UITableViewCellAccessoryNone
- (void)viewDidLoad {
self.mySavedFruitsArray = [myDBOperations getMyFruitsList:[appDelegate getDBPath]:self.myId];
}
/ Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------
{
static NSString *CellIdentifier = #"PoemTypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"MyIdentifier"]autorelease];
}
NSDictionary *aDict = [self.myFruitsArr objectAtIndex:indexPath.row];
NSString *aValue = [aDict objectForKey:#"value"];
NSString *aId = [aDict objectForKey:#"key"];
cell.textLabel.text = aValue;
cell.accessoryType = UITableViewCellAccessoryNone;
NSDictionary *aSavedDict = [self.mySavedFruitsArray objectAtIndex:indexPath.row];
NSString *Value = [aSavedDict objectForKey:#"value"];
NSString *Id = [aSavedDict objectForKey:#"key"];
if ( aId == Id ){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
mySavedFruitsArray - it holds the user selected fruits.
myFruitsArr - this has common list of fruits
now i would like to know how to display UITableViewCellAccessoryCheckmark for cell which matches with mySavedFruitsArray.
I mean , in this edit view i want to display the fruits list with user selected option.
Pls let me know how to do that.
I tried like this, but no use.
/ Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------
{
static NSString *CellIdentifier = #"PoemTypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"MyIdentifier"]autorelease];
}
NSDictionary *aDict = [self.myFruitsArr objectAtIndex:indexPath.row];
NSString *aValue = [aDict objectForKey:#"value"];
NSString *aId = [aDict objectForKey:#"key"];
cell.textLabel.text = aValue;
cell.accessoryType = UITableViewCellAccessoryNone;
NSDictionary *aSavedDict = [self.mySavedFruitsArray objectAtIndex:indexPath.row];
NSString *Value = [aSavedDict objectForKey:#"value"];
NSString *Id = [aSavedDict objectForKey:#"key"];
if ( aId == Id ){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
pls note self.mySavedFruitsArray may not be equal to myFruitsArr always ( because user may select only one fruit).
if ( aId == Id ){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
string comparison is wrong. You should compare strings this way:
if([aId isEqualToString:Id]) {
....
}
instead of checking if ( aId == Id ) which compares the strings as identical objects,
use if ([aID isEqualToString:Id]) which compares strings
In a version downloaded yesterday (6/8/14), UITableViewCellAccessoryCheckmark and UITableViewCellAccessoryNone is not valid. It was throwing compiler errors for me. I think you are supposed to use it as an enum, like so:
if item.completed {
cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
} else {
cell!.accessoryType = UITableViewCellAccessoryType.None
}
With this change, my code compiles and the behavior appears in the simulator.
Sorry I don't know which version to look up (UIKit?), I'm new to iOS development.

View rendering in iOS 4.2

I built a custom view to make chat messages according to this tutorial
It is working fine if the app is directly compiled on device.But while creating an ipa file and installing it via iTunes, in iOS 4.2, the height of the chat bubbles are stretched more than the required size and causes overlapping of chat bubbles. But it is working fine in iOS 5.What would be the reason for this?Thanks in advance.
EDIT:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = (NSDictionary *)[messages objectAtIndex:indexPath.row];
NSString *msg = [[dict objectForKey:#"message"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
CGSize textSize = { 260.0, 10000.0 };
CGSize size = [msg sizeWithFont:[UIFont boldSystemFontOfSize:13]
constrainedToSize:textSize
lineBreakMode:UILineBreakModeWordWrap];
size.height += padding*3;
CGFloat height = size.height < 65 ? 65 : size.height;
return height;
}
EDIT 2:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MessageCellIdentifier";
SMMessageViewTableCell *cell = (SMMessageViewTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[SMMessageViewTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if ([messages count]>0) {
NSLog(#"index path is %d",indexPath.row);
NSDictionary *s = (NSDictionary *) [messages objectAtIndex:indexPath.row];
NSString *sender =allTrim([s objectForKey:#"sender"]);
NSString *senderId = [s objectForKey:#"friendId"];
NSString *message = [s objectForKey:#"message"];
if ([message length]<8)
{
message=[message stringByAppendingString:#" "];
}
message=[message stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *time = [s objectForKey:#"time"];
NSString *locatn = [s objectForKey:#"friendLocation"];
CGSize textSize = { 260.0, 10000.0 };
CGSize size = [message sizeWithFont:[UIFont boldSystemFontOfSize:13]
constrainedToSize:textSize
lineBreakMode:UILineBreakModeWordWrap];
size.width += (padding/2);
cell.messageContentView.text = [message stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.userInteractionEnabled = YES;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
UIImage *bgImage = nil;
if ([senderId isEqualToString:UIAppDelegate.userId]) {
sender=#"Me";
bgImage = [[UIImage imageNamed:#"ChatBubbleGray.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
[cell.messageContentView setFrame:CGRectMake(padding, padding*2, size.width, size.height)];
[cell.bgImageView setFrame:CGRectMake( cell.messageContentView.frame.origin.x - padding/2,
cell.messageContentView.frame.origin.y - padding/2,
size.width+padding,
size.height+padding)];
cell.senderAndTimeLabel.textAlignment=UITextAlignmentLeft;
} else {
bgImage = [[UIImage imageNamed:#"ChatBubbleGreen.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
[cell.messageContentView setFrame:CGRectMake(320 - size.width - padding,
padding*2,
size.width,
size.height)];
[cell.bgImageView setFrame:CGRectMake(cell.messageContentView.frame.origin.x - padding/2,
cell.messageContentView.frame.origin.y - padding/2,
size.width+padding,
size.height+padding)];
cell.senderAndTimeLabel.textAlignment=UITextAlignmentRight;
}
cell.bgImageView.image = bgImage;
if ([locatn length]>0)
{
cell.senderAndTimeLabel.text = [NSString stringWithFormat:#"%#, %# %#", sender, locatn, time];
}
cell.senderAndTimeLabel.text = [NSString stringWithFormat:#"%#, %#", sender, time];
}
return cell;
}
Have you tried direct building in release? Typically direct compilation is done with out optimizations applied. I've never heard of this happening but, it's possible some optimization is wacking out your views.
I built [...] according to a tutorial
There's your first programming error. ;)
Kidding aside, running a non-debug executable causes the app to have an uninitialized, non-zeroed heap where the instance variable values are held. If you don't initialize all your instance variables, it may lead to unpredictable behavior. That may be an issue here, but we can't see all the code involved, so we can only bet on what may be wrong. And the code you did attach, doesn't seem to be the problem. It's the drawing of bubbles that's broken.

Adding cell.textLabel.text value to an array and displaying it

i have a UItableView and i have two buttons on each cell. You can add or subtract 1 from the cell's textLabel. I add the cells current value +1 with this:
- (IBAction)addLabelText:(id)sender{
num = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] +1];//<--- num is an NSNumber
number = [[NSMutableArray alloc]initWithObjects:num, nil];//<---- number is an NSMutableArray
[myTableView reloadData];
}
and I am trying to subtract the text and store it in an array with this:
- (IBAction)subtractLabelText:(id)sender
{
if ( [[cell.textLabel text] intValue] == 0){
num = [NSString stringWithFormat:#"%d",[num intValue] +0];
[number addObject:num];
[myTableView reloadData];
}
else{
num = [NSString stringWithFormat:#"%d",[num intValue] -1];
[number addObject:num];
[myTableView reloadData];
}
}
and im trying to set the cell.textLabel.text in the cellForRow like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *identifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
cell.textLabel.text = [number objectAtIndex:indexPath.row];//<---IM USING THIS LINE TO SET THE NEW TEXTLABEL
cell.textLabel.text = #"1";
return cell;
}
MY PROBLEM
So, the addition works, but the subtraction does not. It doesnt work at all when i press the button on the cell. Thanks in advance!!
At the risk of pointing out the obvious... you seem to have hard-coded the text property to #"1".
cell.textLabel.text = [number objectAtIndex:indexPath.row];//<---IM USING THIS LINE TO SET THE NEW TEXTLABEL
cell.textLabel.text = #"1";
The first line is probably doing what you think... but then you're immediately changing it back to #"1".
EDIT - Based on clarification in comments, here's what I think you want to do. I will modify your own code as posted.
Note that I put my addition into viewDidLoad as an example. You could do this in init, or any number of other places, at whatever point you know how many cells you want to show.
- (void)viewDidLoad {
self.number = [[[NSMutableArray alloc] init] autorelease];
for (int i = 0; i < [HOW MANY CELLS DO YOU WANT?]; i++) {
[self.number addObject:#"1"];
}
[myTableView reloadData];
}
- (IBAction)addLabelText:(id)sender {
// Note that I'm assuming here that your button is a direct child of the cell.
// If not, you'll need to change this.
UITableViewCell *cell = [sender superview];
NSInteger newNumber = [cell.textLabel.text intValue] + 1;
NSString *newNumberString = [NSString stringWithFormat:#"%d", newNumber];
[self.number replaceObjectAtIndex:cell.tag withObject:newNumberString];
[myTableView reloadData];
}
- (IBAction)subtractLabelText:(id)sender {
// Note that I'm assuming here that your button is a direct child of the cell.
// If not, you'll need to change this.
UITableViewCell *cell = [sender superview];
NSInteger newNumber = [cell.textLabel.text intValue] - 1;
newNumber = (newNumber < 0) ? 0 : newNumber;
NSString *newNumberString = [NSString stringWithFormat:#"%d", newNumber];
[self.number replaceObjectAtIndex:cell.tag withObject:newNumberString];
[myTableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
cell.tag = indexPath.row; // Important for identifying the cell easily later
cell.textLabel.text = [self.number objectAtIndex:indexPath.row];
return cell;
}
I don't want to get too much more in depth, but I would recommend you take a look at reloading only the cell modified, instead of calling [myTableView reloadData] every time.

Reading plist into TableView

I started this project with a simple plist of a dictionary with two arrays of strings. I now want to add more information and want to use this plist structure:
Root - Dictionary - (2 items)
Standard - Array - (3 items)
Item 0 - Dictionary - (4 items)
Color - String - Red
Rvalue - String - 255
Gvalue - String - 0
Bvalue - String - 0
Sorry about typing in the plist but the site would not let me post an image
I know that the RGB values could be numbers instead of strings but I have a reason for them being strings.
This is the code I used to read the simple plist:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *colorSection = [colors objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if(cell == nil){
cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: SectionsTableIdentifier] autorelease];
}
cell.textLabel.text = [colorSection objectAtIndex:row];
[cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton]; //add disclosure button to rows
return cell;
}
My question is what is the specific code to retrieve the contents of the color dictionaries to get the Colors for the cell.textLabel.text and also read the RGB values to add a subtitle. I've been working on this for several days and have read references and lots of examples and unfortunately can't solve the problem. Your assistance will be greatly appreciated.
So providing you have your Standard - Array stored against a Array you've defined in your .h file then something like this would work. In this example the array is stored against self.coloursArray.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if(cell == nil){
cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: SectionsTableIdentifier] autorelease];
}
NSString* ColourString = [[self.coloursArray objectAtIndex:indexPath.row] valueForKey:#"Colour"];
NSString* rValue = [[self.coloursArray objectAtIndex:indexPath.row] valueForKey:#"Rvalue"];
NSString* gValue = [[self.coloursArray objectAtIndex:indexPath.row] valueForKey:#"Gvalue"];
NSString* bValue = [[self.coloursArray objectAtIndex:indexPath.row] valueForKey:#"Bvalue"];
cell.textLabel.text = ColourString;
NSString* subCellString = [NSString stringWithFormat:#"%#:%#:%#", rValue, gValue, bValue];
}
Hopefully that'll give a a hand.
First, do not use -[UITableViewCell initWithFrame:reuseIdentifier:]. It has been deprecated and will give you a warning, plus it will make your subtitle harder to implement. This code is a modified version of yours which loads the information, sets the title to the Color property, and sets the subtitle to a string containing the Rvalue, Gvalue, and Bvalue properties.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *colorSection = [colors objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if(cell == nil) {
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: SectionsTableIdentifier] autorelease];
}
NSDictionary *color = [colorSection objectAtIndex:row];
cell.textLabel.text = [color objectForKey:#"Color"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#, %#, %#",[color objectForKey:#"Rvalue"],[color objectForKey:#"Gvalue"],[color objectForKey:#"Bvalue"]];
[cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton]; //add disclosure button to rows
return cell;
}