Saving values in UITableCellView to custom class - ios

I have an iOS app that makes a request to a web-service which returns JSON formatted data. There is a predefined class in my iOS app that inherits and implements the JSONModel Framework, to which this returned data is bound to as an NSMutableArray containing these objects. The TableView's data is generated from these objects.
My conundrum is that in my custom UITableViewCell I allow the user to change some of the data presented, and I need the ability to save that back to the classes which can be serialized and sent via POST back to the web-service.
Custom Cell .h:
#interface EnclosureDetailCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *enclosureNumber;
#property (weak, nonatomic) IBOutlet UITextField *QTY;
#property (weak, nonatomic) IBOutlet UIStepper *stepper;
#property (weak, nonatomic) IBOutlet DeSelectableSegmentControl *enclosureStatus;
- (IBAction)valueChanged:(UIStepper *)sender;
- (IBAction)changedTextValue:(id)sender;
#end
Custom Cell .m:
#implementation EnclosureDetailCell
- (IBAction)changedTextValue:(id)sender
{
self.stepper.value = self.QTY.text.intValue;
}
- (IBAction)valueChanged:(UIStepper *)sender
{
int stepperValue = sender.value;
self.QTY.text = [NSString stringWithFormat:#"%i", stepperValue];
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
Model Class (.h):
#protocol Enclosure #end
#interface Enclosure : JSONModel
#property (nonatomic, strong) NSString *EnclosureNumber;
#property (nonatomic, strong) NSString *InventoryID;
#property (nonatomic, strong) NSString *UseInventoryID;
#property (nonatomic) int CensusQTY;
#property (nonatomic) BOOL Verified;
#property (nonatomic) BOOL MissingEnclosure;
#property (nonatomic) BOOL RetireEnclosure;
#end
TableViewController (partial)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
EnclosureDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
ProtocolEnclosure *loc = (ProtocolEnclosure *)_objects[indexPath.section];
Enclosure *enc = (Enclosure *) loc.Enclosures[indexPath.row];
cell.enclosureNumber.text = enc.EnclosureNumber;
cell.QTY.text =[NSString stringWithFormat:#"%i", enc.CensusQTY];
cell.stepper.value = enc.CensusQTY;
if (enc.Verified)
{
cell.QTY.enabled = false;
cell.stepper.enabled = false;
cell.enclosureStatus.selectedSegmentIndex = Verified;
}
else if (enc.MissingEnclosure)
cell.enclosureStatus.selectedSegmentIndex = MissingEnclosure;
else if (enc.RetireEnclosure)
cell.enclosureStatus.selectedSegmentIndex = RetireEnclosure;
else
cell.enclosureStatus.selectedSegmentIndex = None;
return cell;
}
enum{
Verified = 0,
MissingEnclosure = 1,
RetireEnclosure = 2,
None = -1
};
So in my UITableViewCell I have a text field that corresponds to CensusQTY and a SegmentControl who's selection corresponds to Verified/MissingEnclosure/RetireEnclosure.
How can I go about saving the data the user has changed via the UI back into the model class?
I obviously can't iterate over each of the UITableView rows - because of dequeue, I will only get the ones that are currently on screen.
Any thoughts on how this could be accomplished?
Thanks!

There are probably many ways to do that, the cleanest way that comes to mind would be to create a delegate for your custom cell. (That you could declare in .h). Your cell should add a index property to keep track of what instance of Enclosure it's referring to.
#class EnclosureDetailCell;
#protocol EnclosureCellDelegate
#required
- (void) qtyDidUpdate:(EnclosureDetailCell*)cell;
- (void) stepperDidUpdate:(EnclosureDetailCell*)cell;
#end
#interface EnclosureDetailCell : UITableViewCell
#property (nonatomic,assign) NSInteger index;
#property (nonatomic,weak) id<EnclosureCellDelegate> delegate;
....
In your .m you would have to call your delegate
#implementation EnclosureDetailCell
- (IBAction)changedTextValue:(id)sender
{
self.stepper.value = self.QTY.text.intValue;
[self.delegate qtyDidUpdate:self];
}
- (IBAction)valueChanged:(UIStepper *)sender
{
int stepperValue = sender.value;
self.QTY.text = [NSString stringWithFormat:#"%i", stepperValue];
[self.delegate stepperDidUpdate:self];
}
You'd have to implement those methods in your TableViewController. It would look like :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
EnclosureDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.index = indexPath.row;
cell.delegate = self;
ProtocolEnclosure *loc = (ProtocolEnclosure *)_objects[indexPath.section];
Enclosure *enc = (Enclosure *) loc.Enclosures[indexPath.row];
....
}
- (void) qtyDidUpdate:(EnclosureDetailCell*)cell{
Enclosure *enc = (Enclosure *)loc.Enclosures[cell.index];
//Here you can update directly the items of your array
}
- (void) stepperDidUpdate:(EnclosureDetailCell*)cell{
Enclosure *enc = (Enclosure *)loc.Enclosures[cell.index];
//Here you can update directly the items of your array
}
That way you will be able to keep your whole array updated, and be able to send your new data to your web service whenever you like.

Probably the easiest way would be to have the cell own a weak reference to the Model object which you update in the IBAction methods of the cell.
#interface EnclosureDetailCell : UITableViewCell
...
#property(nonatomic, weak) Enclosure *enclosure;
...
#end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
Enclosure *enc = (Enclosure *) loc.Enclosures[indexPath.row];
cell.enclosure = enc;
...
}
#implementation EnclosureDetailCell
- (IBAction)changedTextValue:(id)sender
{
self.stepper.value = self.QTY.text.intValue;
//you have access to self.enclosure, do what you want
}
- (IBAction)valueChanged:(UIStepper *)sender
{
int stepperValue = sender.value;
self.QTY.text = [NSString stringWithFormat:#"%i", stepperValue];
//you have access to self.enclosure, do what you want
}

Related

Call and use uitableview from uitableviewcell?

I have a UITableViewController with many UITableViewCell. Each Cell have a UISwitch Button.
Here is my UITableViewController Class:
#implementation DanhsachTableViewController{
NSMutableArray *data;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DichVu2TableViewCell *cell = (DichVu2TableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"dscell"];
NSDictionary *dataCell = data[indexPath.row];
cell.service = dataCell[#"service"];
cell.package = dataCell[#"package"];
cell.loai_goi = dataCell[#"loai_goi"];
return cell;
}
-(void) changeCellState:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi{
for (int i =0;i<data.count;i++){
DichVu2TableViewCell *cellLocal = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
if ([service isEqualToString:cellLocal.service] && ![package isEqualToString:cellLocal.package] && [loai_goi isEqualToString:cellLocal.loai_goi]){
[cellLocal.sudung setOn:NO animated:YES];
}
}
}
"Data" array was loaded in method loadData (not important here so I don't include it).
In UITableViewCell (class name: DichVu2TableViewCell), I set event Value Change of Switch so that each time a Switch change value (ON for example), all other cell's switch which have the same value "service" and "loai_goi" will be set OFF.
DanhsachTableViewController *tableview = [[DanhsachTableViewController alloc] init];
tableview.tableView.delegate = (DanhsachTableViewController *)self.superview.superview;
[tableview changeCellState:_service package:_package loaigoi:_loai_goi];
But when I call, the array "data" of above tableview have 0 object so nothing happened.
Is there any way to do that?
Hi Oyeoj,
Thanks for your help.
I have a little problem when followed your guide. There are some error in xcode when I use extract your code so I have to customize. But the program still has error when running. Would you please help me review my code. Thanks in advance.
DichVu2TableViewCell.h
#class DichVu2TableViewCell;
//Change : NSObject to <NSObject> because XCode 6.3 has error.
#protocol DichVu2TableViewCellDelegate <NSObject>
-(void)changeCell:(DichVu2TableViewCell *)sender state:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi;
#end
#interface DichVu2TableViewCell : UITableViewCell
#property (weak) id <DichVu2TableViewCellDelegate> delegate;
#end
DichVu2TableViewCell.m
#implementation DichVu2TableViewCell
….
- (void)someSwitchingEvent
{
[self.delegate changeCell:self state:_service package:_package loaigoi:_loai_goi];
}
#end
DanhsachTableViewController.h
#interface DanhsachTableViewController : UITableViewController
#property (strong,nonatomic) NSString *loaitb;
#property (strong,nonatomic) NSString *type;
#property (strong,nonatomic) NSString *name;
#property NSMutableArray *pre_inuse_;
#property NSMutableArray *data_inuse_;
#property NSMutableArray *vas_inuse_;
#end
DanhsachTableViewController.m
#import "DichVu2TableViewCell.h"
//Change <DichVu2TableViewCellDelegate> to (DichVu2TableViewCellDelegate) because XCode 6.3 has error.
#interface DanhsachTableViewController (DichVu2TableViewCellDelegate)
#property (nonatomic) NSIndexPath *forUpdateIndexPath;
#end
#implementation DanhsachTableViewController{
NSMutableArray *data;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DichVu2TableViewCell *cell = (DichVu2TableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"dscell"];
NSDictionary *dataCell = data[indexPath.row];
cell.service = dataCell[#"service"];
cell.package = dataCell[#"package"];
cell.loai_goi = dataCell[#"loai_goi"];
cell.kieu_goi = dataCell[#"kieu_goi"];
[cell.sudung setOn:NO animated:YES];
cell.delegate = self;
//Change cellLocal —> cell because there are no cellLocal avaiable. And Program error when run to this row.
[cell.sudung setOn:(self.forUpdateIndexPath == indexPath) animated:YES];
return cell;
}
-(void)changeCell:(DichVu2TableViewCell *)sender state:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi
{
//Add cellLocal —> cell because there are no cellLocal avaiable
DichVu2TableViewCell *cellLocal = (DichVu2TableViewCell *)[self.tableView cellForRowAtIndexPath:self.forUpdateIndexPath];
if ([service isEqualToString:cellLocal.service] && ![package isEqualToString:cellLocal.package] && [loai_goi isEqualToString:cellLocal.loai_goi]){
// get the indexPath of the cell
self.forUpdateIndexPath = [self.tableView indexPathForCell:sender];
// update the date source
NSMutableDictionary *dataCell = [data[self.forUpdateIndexPath.row] mutableCopy];
[dataCell setObject:service forKey:#"service"];
[dataCell setObject:package forKey:#"package"];
[dataCell setObject:loai_goi forKey:#"loai_goi"];
// you dont need the for-statement just reload the table
[self.tableView reloadData];
// then update the switch inside `- cellForRowAtIndexPath`
}
}
A more efficient method would be to use custom delegates.
You can declare a protocol in your UITableViewController class.
Declare the changeCellState function in the protocol.
Create a delegate property in the UITableViewCell class.
Call the delegate method from the UITableViewCell class when the switch value is changed.
The UITableViewController will itself receive the message, and the function will be called respectively.
Have you tried logging self.superview.superview; ? are your sure is in type UIViewController?
if so:
Do not call [[DanhsachTableViewController alloc]
instead use the DanhsachTableViewController from your parentview
DanhsachTableViewController *tableview = (DanhsachTableViewController *)self.superview.superview;
[tableview changeCellState:_service package:_package loaigoi:_loai_goi];
This
DanhsachTableViewController *tableview = [[DanhsachTableViewController alloc] init]; assigns a new DanhsachTableViewController class and not the existing one.
Edit
USING protocol and delegate
When using delegate you dont need the self.superview.superview :)
UNDER DichVu2TableViewCell
#class DichVu2TableViewCell;
#protocol DichVu2TableViewCellDelegate <NSObject>
-(void)changeCell:(DichVu2TableViewCell *)sender state:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi;
#end
#interface DichVu2TableViewCell : UIViewController
#property (weak) id <DichVu2TableViewCellDelegate> delegate;
#end
#implementaion DichVu2TableViewCell
..
- (void)someSwitchingEvent
{
[self.delegate changeCell:self state:_service package:_package loaigoi:_loai_goi];
}
#end
while
UNDER DanhsachTableViewController
// assuming you alreading imported the `DichVu2TableViewCell` like
//
// #import "DichVu2TableViewCell.h"
//
// set the delegate
#interface DanhsachTableViewController () <DichVu2TableViewCellDelegate>
#property (nonatomic) NSIndexPath *forUpdateIndexPath;
#end
// then implement the method from the delegate under implementation file
#implementation DanhsachTableViewController
{
NSMutableArray *data;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DichVu2TableViewCell *cell = (DichVu2TableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"dscell"];
NSDictionary *dataCell = data[indexPath.row];
cell.service = dataCell[#"service"];
cell.package = dataCell[#"package"];
cell.loai_goi = dataCell[#"loai_goi"];
// this is the magic .. :)
//--
cell.delegate = self;
[cell.sudung setOn:(self.forUpdateIndexPath == indexPath) animated:YES];
//--
return cell;
}
-(void)changeCell:(DichVu2TableViewCell *)sender state:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi
{
// `self.forUpdateIndexPath` is declared as property
if ([service isEqualToString:service] && ![package isEqualToString:package] && [loai_goi isEqualToString:loai_goi]){
// get the indexPath of the cell
self.forUpdateIndexPath = [self.tableView indexPathForCell:sender];
// update the date source
NSMutableDictionary *dataCell = [data[self.forUpdateIndexPath.row] mutableCopy];
[dataCell setObject:service forKey:#"service"];
[dataCell setObject:package forKey:#"package"];
[dataCell setObject:loai_goi forKey:#"loai_goi"];
// you dont need the for-statement just reload the table
[self.tableView reloadData];
// then the switch will be updated inside `- cellForRowAtIndexPath`
}
}
Hope this is more helpful now.. :) Cheers...

IOS: Not able to access my label in UICell

I am trying to create a table with prototype cell
for that i had taken a tableview and inserted a cell in table view
and in cell i had taken a label in which i want to set values from my Employee class.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
RWTCell *cell = (RWTCell*)[tableView dequeueReusableCellWithIdentifier:#"employeeeCell"];
if (!cell){
cell = [[RWTCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"employeeeCell"];
}
Employee *currentEmp=[employeeArray objectAtIndex:indexPath.row];
NSLog(#" %#",currentEmp.empName);
cell.lName.text=currentEmp.empName;
// cell.textLabel.text = currentEmp.empName;
return cell;
}
Above is my code
when i try to do
RWTCell *cell = (RWTCell*)[tableView dequeueReusableCellWithIdentifier:#"employeeeCell"];
it always gives me null, and this line below never works
cell.lName.text=currentEmp.empName;
my Employee.m class
#import "Employee.h"
#implementation Employee
#synthesize empDepart,empDoj,empDob,empName,empSalary,empGender;
#end
and Employee.h
#import <Foundation/Foundation.h>
#interface Employee : NSObject
#property (nonatomic, retain) NSString *empName;
#property (nonatomic, retain) NSString *empSalary;
#property (nonatomic, retain) NSString *empDob;
#property (nonatomic, retain) NSString *empDoj;
#property (nonatomic, retain) NSString *empGender;
#property (nonatomic, retain) NSString *empDepart;
#end
EDIT
sorry i forgot to mention my cell class
and i am working on storyboard
#import "RWTCell.h"
#implementation RWTCell
#synthesize lName;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
#import <UIKit/UIKit.h>
#interface RWTCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *lName;
#end
Take a look at the custom cell I am using in my application.
.h file of custom cell
#import <UIKit/UIKit.h>
#interface EvalHistoryCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *lblEvaluator;
#property (strong, nonatomic) IBOutlet UILabel *lblDate;
#property (strong, nonatomic) IBOutlet UILabel *lblStore;
#property (strong, nonatomic) IBOutlet UILabel *lblStatus;
#end
.m file of custom cell
#import "EvalHistoryCell.h"
#implementation EvalHistoryCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
in main viewcontroller where you want to use it:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strEvalIdentifier = #"HistoryIdentifier";
EvaluationListEntity *objEvalEntity=[arrmEvalList objectAtIndex:indexPath.row];
EvalHistoryCell *cell = (EvalHistoryCell *)[tableView dequeueReusableCellWithIdentifier:strEvalIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"EvalHistoryCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.lblEvaluator.text=objEvalEntity.strEvaluatorName;
return cell;
}
Try this.
Make sure you connected your custom cell with your view at RWTCell.xib
At your .h file
#property(nonatomic,strong) RWTCell *rwtcell;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier= #"MyIdentifier";
RWTCell *cell = (RWTCell*)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if(cell==nil)
{
[[NSBundle mainBundle] loadNibNamed:#"RWTCell" owner:self options:nil];
cell=self.rwtcell;
}
Employee *currentEmp=[employeeArray objectAtIndex:indexPath.row];
NSLog(#" %#",currentEmp.empName);
cell.lName.text=currentEmp.empName;
return cell;
}
Hope it helps you..

Set label for a custom cell

I have a custom table cell and I'm just trying to set the label, image, etc but for some reason it's not working.
Here is my code for my custom cell
BrowserMenuCell.h
#import <UIKit/UIKit.h>
#interface BrowseMenuCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UIButton *wishListBUtton;
#property (strong, nonatomic) IBOutlet UIImageView *itemImage;
#property (strong, nonatomic) IBOutlet UILabel *itemLabel;
#property (strong, nonatomic) IBOutlet UILabel *itemPrice;
#property (strong, nonatomic) IBOutlet UITextField *quantityField;
#property (strong, nonatomic) IBOutlet UILabel *totalLabel;
- (IBAction)plusButton:(id)sender;
- (IBAction)cartButton:(id)sender;
- (IBAction)minusButton:(id)sender;
#end
BrowserMenuCell.m
#import "BrowseMenuCell.h"
#implementation BrowseMenuCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (IBAction)plusButton:(id)sender {
}
- (IBAction)cartButton:(id)sender {
}
- (IBAction)minusButton:(id)sender {
}
#end
Cell for row at index path
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BrowseMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ItemsCell"];
OfficeSupply *supply = [_items objectAtIndex:indexPath.row];
if(cell == nil)
{
NSArray * views = [[NSBundle mainBundle] loadNibNamed:#"BrowseMenuCell" owner:nil options:nil];
for (id obj in views){
if([obj isKindOfClass:[UITableViewCell class]])
{
BrowseMenuCell * obj = [[BrowseMenuCell alloc]init];
obj.itemLabel.text = supply.itemName;
cell = obj;
break;
}
}
}
return cell;
}
Have you tried using [self.tableView reloadData]?
To start with, don't create a new random instance of the cell after you have already created one from the NIB file. Change the code to this:
for (BrowseMenuCell *obj in views){
if([obj isKindOfClass:[BrowseMenuCell class]])
{
obj.reuseIdentifier = #"ItemsCell";
obj.itemLabel.text = supply.itemName;
cell = obj;
break;
}
}
That won't guarantee it works, but at least the NIB setup of your labels won't be getting thrown away.
If it still doesn't work. Debug. Check the frames of the labels. Check the label references are set (not nil).
This is the wrong way you create cell. Try this one:
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BrowseMenuCell *cell = (BrowseMenuCell*)[tableView dequeueReusableCellWithIdentifier:#"ItemsCell"];
OfficeSupply *supply = [_items objectAtIndex:indexPath.row];
if (_cellObj == nil) {
[[NSBundle mainBundle] loadNibNamed:#"BrowseMenuCell" owner:nil options:nil];
}
cell.itemlabel.text = supply.itemName;
return cell;
}

UIImageView background color but not image displaying

I have a UITableViewCell nib file in which there is a UIImageView and a UILabel. I have outlets for both of these to my controller as well as an outlet for the cell itself. I am setting the label and image programmatically, but the image does not show up.
So I went to test it, and even if I set the image itself in the nib file, it does not show up. If I set the background color, it shows up fine. Any ideas? I'm stuck.
It seems to be unrelated to code, in my mind, since it doesn't even work via nib file. But here it is anyway in case it helps somehow.
MyViewController.h
#interface MyViewController : UITableViewController
#property (strong, nonatomic) MyModel *myModel;
#property (strong, nonatomic) NSArray *tableViewCells;
#property (strong, nonatomic) IBOutlet UITableViewCell *tableViewCell;
#property (weak, nonatomic) IBOutlet UILabel *myLabel;
#property (weak, nonatomic) IBOutlet UIImageView *myImage;
#end
MyViewController.m
#interface MyViewController ()
- (void)bindMyModel:(MyModel*)model toView:(UITableViewCell*)view;
- (UITableViewCell*)copyUITableViewCell:(UITableViewCell*)cell;
#end
#implementation MenuViewController
#synthesize myModel = _myModel;
#synthesize tableViewCells = _tableViewCells;
#synthesize tableViewCell = _tableViewCell;
#synthesize myLabel = _myLabel;
#synthesize myImage = _myImage;
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *cells = [[NSMutableArray alloc] init];
[MyModel loadAndOnSuccess:^(id data, id context) {
self.myModel = data;
for (MyModel *item in self.myModel.items) {
[[NSBundle mainBundle] loadNibNamed:#"TableCellNib" owner:self options:nil];
[self bindMyModel:item toView:self.tableViewCell];
[cells addObject:[self copyUITableViewCell:self.tableViewCell]];
self.tableViewCell = nil;
}
self.tableViewCells = [[NSArray alloc] initWithArray:cells];
} onFail:^(NSString *error, id context) {
NSLog(#"FAIL with error: %#", error);
}];
}
- (void)viewDidUnload
{
[self setTableViewCell:nil];
[self setMyLabel:nil];
[self setMyImage:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void) bindMyModel:(MyModel*)model toView:(UITableViewCell*)view
{
if (view) {
self.myLabel.text = model.myLabelText;
self.myImage.image = model.myImageResource;
self.myLabel = nil;
self.myImage = nil;
}
}
- (UITableViewCell*)copyUITableViewCell:(UITableViewCell*)cell
{
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject: cell];
return [NSKeyedUnarchiver unarchiveObjectWithData: archivedData];
}
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self.tableViewCells objectAtIndex:indexPath.row];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.myModel.items.count;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Irrelevant code here
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return ((UITableViewCell*)[self.tableViewCells objectAtIndex:indexPath.row]).frame.size.height;
}
#end
You are trying to use two IBOutlets on your UITableViewController to populate a multitude of UILabels and UIImageViews that are part of the UITableViewCell. You need to create a custom subclass of UITableViewCell and add the IBOutlets to that subclass.
#interface CustomCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *myLabel;
#property (weak, nonatomic) IBOutlet UIImageView *myImage;
#end
then in your bindMyModel:toView:
- (void) bindMyModel:(MyModel*)model toView:(CustomCell*)view
{
if (view) {
view.myLabel.text = model.myLabelText;
view.myImage.image = model.myImageResource;
}
}
Now you have independent IBOutlets for each of your Cells. You will also need to change some of your bindings as well. This is a fix, but honestly I would rewrite a lot of the code and just use dequeueReusableCellWithIdentifier in your cellForRowAtIndexPath call, and keep a pool of CustomCells that you will reuse, and just set up the myLabel.text and myImage.image in the cellForRowAtIndexPath call.

Can't access the IBOutlets of my custom cell on cellForRowAtIndexPath

I made a custom cell with a XIB:
.h
#import <UIKit/UIKit.h>
#interface TWCustomCell : UITableViewCell {
IBOutlet UILabel *nick;
IBOutlet UITextView *tweetText;
}
#end
.m
#import "TWCustomCell.h"
#implementation TWCustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
And I load them in cellForRowAtIndexPath: in this way:
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
TWCustomCell *cell = (TWCustomCell*)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:#"TWCustomCell" owner:nil options:nil];
for (id currentObject in topLevelObject) {
if([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (TWCustomCell*) currentObject;
break;
}
}
}
// Configure the cell...
cell.tweetText.text = [tweets objectAtIndex:indexPath.row];
return cell;
}
On cell.tweetText.text = [tweets objectAtIndex:indexPath.row];
On the dot after cell, Xcode tells me_ "Property 'tweetText' not found on object of type 'TWCustomCell *'; did you mean to access ivar 'tweetText'?" and tells me to replace it with
cell->tweetText.text. But there appears the error: "Semantic Issue: Instance variable 'tweetText' is protected". What do I have to do?
You didn't declare a property that will allow access to the IBOutlets outside of the class with the dot syntax.
Here's how i would do it:
in your .h file:
#property (nonatomic, readonly) UILabel *nick;
#property (nonatomic, readonly) UITextView *tweetText;
in the .m:
#synthesize nick, tweetText;
Or you could remove the ivar IBOutlets and declare the properties as retain and IBOutlets like this:
#property (nonatomic, retain) IBOutlet UILabel *nick;
#property (nonatomic, retain) IBOutlet UITextView *tweetText;
The problem was with my custom cell ivars:
#import <UIKit/UIKit.h>
#interface TWCustomCell : UITableViewCell {
//added here #public and you can access them now
#public
IBOutlet UILabel *nick;
IBOutlet UITextView *tweetText;
}
#end

Resources