ipad add tableview (only a part) to viewcontroller with storyboard - cocoa-touch

So I'm trying to add a UITableView on the lower half of my ipad app which will be used to display a search result. This is how I did it.
I added a UIView
I added a UItableView onto the UIView
I then dragged the UITableView to the ViewController so it can connect to it for delegate and datasource.
This is what it currently looks like:
(It's at that middle top row)
So I added the following onto the viewcontroller class to generate the data
# pragma mark TableView properties
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SearchResultCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = #"test";
}
The debugger would go through all these but would get stuck after the "cellForRowAtIndexPath" method:
It would just go through that and would not end until I stop the whole debugging. Not really sure what's going on.
Thoughts? Maybe you guys can point me to the right direction as to how I should generate my search results.
Thanks!

I usually find it much more faster and easier to use the free Sensible TableView framework to do automatic table view searches, instead of using the regular datasource/delegate system which I could never get right.

Related

Cell text overlaps the editingAccessory when try to delete a row in iOS7

When I compile my app in the new iOS7, I found a problem when entering in the edit mode of an UITableView.
When I press in the red minus button to delete a row of the table, this row indent to the left to let appear the 'Delete' button. However, when this button appears, the text of the cell overlaps the editingAccesory (this happens only when the text is longer than the length of the cell).
How can I remove the overlapping?
Edit: Images in the comments
Edit 2: Tis is the code of the creation of the table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_tweetList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SessionDetailCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Tweet *tweet = [_tweetList objectAtIndex:indexPath.row];
cell.textLabel.text = tweet.text;
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[tableView beginUpdates];
Tweet *deletedTweet = [_tweetList objectAtIndex:indexPath.row];
[_selectedSession removeTweetsObject:deletedTweet];
[deletedTweet deleteEntity];
_tweetList = [Tweet findAllSortedBy:#"index" ascending:YES withPredicate:[NSPredicate predicateWithFormat:#"session == %#",_selectedSession]];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
}
[[NSManagedObjectContext defaultContext]saveToPersistentStoreWithCompletion:nil];
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
selectedPath = indexPath;
[self performSegueWithIdentifier:#"EditTweet" sender:self];
}
Solution:
Finally, I put the accessoryButton in the default state, and I use the edit state only to delete the rows. It's the only solution I've found :(
Perhaps, the method "willTransitionToState" can help people to solve similar problems.
You can hide or remove editingAccesory in editing mode , so there is no overlapping there,
set this,
Screenshot:
I came across this question, because in iOS 8.3 I faced the same problem, that it seems not possible to correctly display the editing accessory AND the delete confirmation without the cell content and the accessory item to overlap. Solving this issue without breaking the transition-animations was quite a challenge. ;)
So here is my solution (assuming that you are using autolayout constraints in IB):
Create a UITableViewCell subclass and link it to your table view cell in IB.
Add an outlet from the autolayout constraint specifying the horizontal spacing bewteen the right-most view and the cell's content view (trailing to margin).
Override willTransitionToState and layoutSubviews as shown below.
Table cell subclass:
#IBOutlet weak var horizontalSpaceConstraint: NSLayoutConstraint!
override func willTransitionToState(state: UITableViewCellStateMask) {
if (state & UITableViewCellStateMask.ShowingDeleteConfirmationMask == UITableViewCellStateMask.ShowingDeleteConfirmationMask) {
self.horizontalSpaceConstraint.constant = 49.0; // ugly, delete-confirmation width
}
super.willTransitionToState(state)
}
override func layoutSubviews() {
if (!self.showingDeleteConfirmation) {
self.horizontalSpaceConstraint.constant = 0.0;
}
super.layoutSubviews()
}
The reason why I cannot use didTransitionToState() (and use layoutSubviewsinstead) to reset the layout constraint is, that this function is simply not invoked (as of iOS 8.3) after transitioning from the delete-confirmation-state. It seems Apple did only handle the case, that the user actually deletes the row, but not the case that the delete-confirmation is closed without deleting the row. :(

UITableView Data Inconsistency

I have a UITableView backed by a NSArray.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
id item = [self.data objectAtIndex:indexPath.row];
cell.item = item;
return cell;
}
Very standard. Now the problem is that reloadData will ask for numberOfSections and numberOfRows synchronously, but will call cellForRow asynchronously. So sometimes, by the time cellForRowAtIndexPath gets called, the data array has changed, and so [self.data objectAtIndex:indexPath.row] gets an out of bounds exception and crashes the app. How do I avoid this?
Note that every time I set the data array, I also call [self.tableView reloadData].
cellForRowAtIndexPath gets called frequently, (on scroll etc), you could just add a simple line of code to check if the size of the data array is smaller than the cell being requested. Although this means you might end up with blank cells.
I'd set breakpoints on both methods, right click the breakpoints -> "edit breakpoint" and tick "automatically continue after evaluating". Then click "add action" -> "debugger command" and then type "po data" or "po [data count]".
This will print information about the array in the debug console every time the breakpoint is hit (without stopping). You should then be able to look through the debug output and see where it is falling out of sync. Add some NSLog statements to to tell you which method is is being called etc and work from there.
I think the best way to avoid such a situation is to avoid user interaction while data is updated.May be you can show a screen to user that "updating.." and an activity indicator.
Another way is that to have another array to populate new data, handling can be done in separate thread and at times only it is assigned back to the datasource array with reloading call after that.There also a screen with same can be used while datasource array gets changed
Quick hack I used, try this and see if it works for you:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
// -----------------------------------------------------------------
// the magical line that prevents the table from fetching the data
// -----------------------------------------------------------------
if([indexPath row] < [self.data count])
{
id item = [self.data objectAtIndex:indexPath.row];
cell.item = item;
}
return cell;
}
:D
You should store a local array, that doesnt get modified. then, when your base array changes, you can update your storred array safely. Look into adding/removing cells from a table view using the built in api Add rows to existing UITableView section

Setting static cells in uitableview programmatically

I am programmatically creating a tableview in objective c. How can I make the cells static programmatically?
Thanks
Making cells static programmatically doesn't really make sense. Static cells are basically only for Interface Builder and requires the entire TableView to be static. They allow you to drag UILables, UITextFields, UIImageViews, etc. right into cells and have it show up just how it looks in Xcode when the app is run.
However, your cells can be "static" programmatically by not using an outside data source and hardcoding everything, which is usually going to be kind of messy and generally a poor idea.
I suggest making a new UITableViewController with a .xib and customizing it from there if you want "static" cells. Otherwise, just hardcode all your values and it's basically the same thing, but is probably poor design if it can be avoided.
By using a distinct cell identifier for each one you will get it. You could use something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:#"s%i-r%i", indexPath.section, indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
//you can customize your cell here because it will be used just for one row.
}
return cell;
}
You could also do it the old fashioned and just create the cell the way you want depending on the NSIndexPath, this works with Static Cell TVC's and regular table views (don't forget to return the proper number of sections and rows in their datasource methods):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch indexPath.row {
case 0:
// First cell, setup the way you want
case 1:
// Second cell, setup the way you want
}
// return the customized cell
return cell;
}
I you want to create cells structure for example for a settings screen or something like that and you maybe need just to modify some cells content but not their number or sections structure you can overload method of your UITableViewController subclass like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *aCell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
// Configure the cell...
if ([aCell.reuseIdentifier isEqualToString:#"someIdentifier"]){
//some configuration block
}
else if ([aCell.reuseIdentifier isEqualToString:#"someOtherIdentifier"]) {
//other configuration block
}
return aCell;
}
But you can make it in a better way with a little bit more code;
1) In the begining of your .m file add typedef:
typedef void(^IDPCellConfigurationBlock)(UITableViewCell *aCell);
2) add cellConfigurations property to your TablviewControllerSubclass extention:
#interface IPDSettingsTableViewController ()
#property (nonatomic, strong) NSDictionary *cellConfigurations;
#property (nonatomic) id dataModel;
#end
3) Modify your static cells of TableviewController subclass in storyboard or xib
and add unique cellReuseIdentifier for each cell you want to modify programmatically
4) In your viewDidLoad method setup cellsConfiguration blocks:
- (void)viewDidLoad
{
[super viewDidLoad];
[self SetupCellsConfigurationBlocks];
}
- (void)SetupCellsConfigurationBlocks
{
//Store configurations code for each cell reuse identifier
NSMutableDictionary *cellsConfigurationBlocks = [NSMutableDictionary new];
//store cells configurations for a different cells identifiers
cellsConfigurationBlocks[#"someCellIdentifier"] = ^(UITableViewCell *aCell){
aCell.backgroundColor = [UIColor orangeColor];
};
cellsConfigurationBlocks[#"otherCellIdentifier"] = ^(UITableViewCell *aCell){
aCell.imageView.image = [UIImage imageNamed:#"some image name"];
};
//use waek reference to self to avoid memory leaks
__weak typeof (self) weakSelf = self;
cellsConfigurationBlocks[#"nextCellIdentifier"] = ^(UITableViewCell *aCell){
//You can even use your data model to configure cell
aCell.textLabel.textColor = [[weakSelf.dataModel someProperty] isEqual:#YES] ? [UIColor purpleColor] : [UIColor yellowColor];
aCell.textLabel.text = [weakSelf.dataModel someOtherProperty];
};
weakSelf.cellConfigurations = [cellsConfigurationBlocks copy];
}
5) overload tableView:cellForRowAtIndexPath method like this:
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *aCell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
// configure cell
[self configureCell:aCell withConfigurationBlock:self.cellConfigurations[aCell.reuseIdentifier]];
return aCell;
}
- (void)configureCell:(UITableViewCell *)aCell withConfigurationBlock:(IDPCellConfigurationBlock)configureCellBlock
{
if (configureCellBlock){
configureCellBlock(aCell);
}
}
It is pretty common to want to build a simple table to use as a menu or form, but using the built in API with the datasource and delegate callbacks don't make it easy to write or maintain. You may need to dynamically add/remove/update some cells, so using Storyboards by itself won't work.
I put together MEDeclarativeTable to programmatically build small tables. It provides the datasource and delegate for UITableView. We end up with an API where we provide instances of sections and rows instead of implementing datasource and delegate methods.

Bad EXC_BAD_ACCESS when scrolling through UITableView

I initiated a UITableView with the following code:
ProductTableView *tableProd = [[ProductTableView alloc]initWithNibName:#"ProductTableView" bundle:nil];
the xib file does exist!
Since I am displaying this table in a separate UIView I add it to this screen by:
[content addSubview:tableProd.view];
I used xcode to create a standard UITableView and set the following functions:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = #"test";
return cell;
}
The table is displayed in the simulator with 10 rows filled with test. However, when I start scrolling, and the first cell leaves the screen, the simulator crashes with a EXC_BAD_ACCESS error. I tried using Instruments to detect the NSZombie and the software flaged the zombie. Unfortunately I cant trace this error back to the cause.
Does anyone have a idea what is going wrong here?
if you're adding the view of a view controller as a subview of another view controllers view, i would guess that the ProductTableView view controller is being dealloced (since adding as a subview retains the view, but not the view controller it belongs to)
add the ProductTableView view controller as a property of the container view controller so that it is retained

Confusion with storyboard and UITableView data source: How to display text in a cell

So I've been given an assignment in my Mobile apps class: make a color game app for the iphone.(The description of how to game works is at the top of the pasted viewcontroller.h file below.)
I'm very new to Objective-C and cocoa, but have managed to troubleshoot and fix a lot of things in this app. The problem I have right now is that I don't know how to properly initialize and send UITableViewCells to the view. I'm confused because all of the tutorials I've found online use datasource methods to change different attributes of the UITableView and the cells as well. I'm not sure how these methods will interact with the controls I've already placed. I'm confused because I added them by the storyboard file, not by defining tableview attributes with datasource code.
My immediate issue is that my program won't display the proper text to the cells textlabel and detailtextlabel.
I've looked everywhere online for UITableView and UITableViewCell tutorials, but they are all from years ago and I'm not sure if the advent of the storyboard has changed the way I would treat these controls.
All of the code I've written is either in the viewcontroller.m or viewcontroller.h files.
The method within ViewController.m file, that should call the cell and display text and detail text:
-(IBAction)enterClicked
{
//On enter- send instance colors to the colorTable row[i], perform comparisons and append the resulting symbols to the instanceResults String. Send instanceResults string to the resultTable row[i]. When game counter reaches 6, gameOver. If on comparisons check, the instanceColors are the same as the gameColors, then the player wins.
[self checkForLoss];
if(!self.gameOver)
{
resultOfGuess = [self comparePlayerInputToGameColors:guessColors];
[listOfGuesses addObject:guessColors];
[listOfOutcomes addObject:resultOfGuess];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_numberOfTurnsPlayed inSection:0];
UITableViewCell *thisCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
thisCell.textLabel.text = [self.listOfGuesses lastObject];
thisCell.detailTextLabel.text = [self.listOfOutcomes lastObject];
[guessColors setString:#""];
if([self checkForWin:resultOfGuess])
[UpdateLabel setText:#"You have won!"];
else
[UpdateLabel setText:#""];
self.colorCounter = 0;
self.isStepOne = YES;
_numberOfTurnsPlayed++;
}
else
{
if([self checkForLoss])
[UpdateLabel setText:#"You have lost!"];
}
}
The UITableView DataSource Methods I've called at the bottom of the viewcontroller.m file:
#pragma mark - UITableViewDataSource protocol
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(section == 0)
return #"Guesses: Results:";
return 0;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 6;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
return cell;
}
So my questions are: Can I change a control's properties with datasource methods, if I created the controls through the storyboard? How do I properly display the text in a uitableview's cells?
Edit/update: Thank you, I've used your advice jrturton, but now I've found something peculiar that may be the source of my problems. in my viewController.h file I've changed my header from
ViewController: UIViewController to ViewController: UITableViewController
Thinking that the datasource methods I call within the viewcontroller files have to be able to call the same methods and properties of the class that I call in the header-- Also, I see this done in other UITableView tutorial files.
The problem is that when I change the header to read-- ViewController: UITableViewController -- and I try to compile, I get this error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] loaded the "2-view-3" nib but didn't get a UITableView.'
It compiles fine if I use just :UIViewController in the header file though.
Any ideas?
Further update: I''ve noticed within my storyboard that the only available ViewController object is a UIViewController object, while in the other tutorial files I've seen, this ViewController object is a UITableViewController object. I imagine this is my problem, but I can't seem to switch my UIViewController object to a UITableViewController. All I can do is create a new one, which isn't what I want, I imagine.
Your action method should update the data model (which I think it does, since it changes your listOfGuesses array). You then need to let your table view know that you have added or updated rows so that it can re-load them for you - check the UITableView documentation for reloading data or specific rows.
Creating a cell outside of the datasource methods isn't going to let that cell appear in your table.
At the moment I'm guessing you have 6 empty cells in your table view? You need to populate the text and detail labels in your cellForRowAtIndexPath method. The difference now there are storyboards is that you don't need to do the if (cell == nil) bit, as long as you have set the re-use identifier in your storyboard prototype cell then it will do all that for you. So your cellForRowAtIndexPath method can be reduced to:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
// This will dequeue or create a new cell based on the prototype in your storyboard
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
// Put your actual configuration here based on your model array
cell.textLabel.text = #"Hello";
return cell;
}
Further hints (this is homework so I'm not giving full samples)
'indexPath.row` in the above method will give you the index from your model array that the cell refers to
You have defined the table as having 6 rows, but you are adding items to your model arrays as you go - so when the table asks for row 5, and your model only has 3 entries, you need to deal with this. Consider changing the number of rows in the table dynamically and using table view methods to indicate that new rows have been added. Again, see the UITableView documentation for this.
Typically the text is set in each cell by accessing the setText property:
[[cell textLabel] setText:#"static string"];
or
[[cell textLabel] setText:someNSString];
or with .dot notation
cell.textLabel.text = someNSString;
return cell;
BTW this is done in the method:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath: