How can I select a cell without touching the screen? - objective-c

I have a UITableViewController and want to move down a cell in my table every time the accelerometer's X axis is greater then 0.5 (when this event occurs i increment a value named "TEST" ). How can i change the background of a cell that has it's indexPath.row equal to TEST ?
Here is how i try to access the method(from the accelerometer function) but it gives me an error :
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
if(acceleration.x>0.5)
TEST++;
if(TEST<0) TEST=0;
if(TEST>19) TEST=19;
NSIndexPath *temp = [[NSIndexPath alloc] initWithIndex:TEST];
[self tableView:[self tableView] didSelectRowAtIndexPath:temp];
}
I have 20 rows in my table (hence the clamp).

selectRowAtIndexPath:animated:scrollPosition:
Selects a row in the receiver identified by index path, optionally scrolling the row to a location in the receiver.
(void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition
Parameters
indexPath
An index path identifying a row in the receiver.
animated
YES if you want to animate the selection and any change in position, NO if the change should be immediate.
scrollPosition
A constant that identifies a relative position in the receiving table view (top, middle, bottom) for the row when scrolling concludes. See “Table View Scroll Position”
here
   NSIndexPath *temp = [[NSIndexPath alloc] initWithIndex:TEST];
[self.tableview selectRowAtIndexPath:temp animated:YES scrollPosition:UITableViewScrollPositionNone];

How about scrollToRowAtIndexPath:atScrollPosition:animated:?

Related

How to get elements inside a selected row in a NSTableView?

I have an NSTableView of content type View Based with two columns.
My objects are structured as follows:
Table View
Table Column
Table Cell View
Text Field
Table Column
Table Cell View
Popup Button
For a selected row, I want to get an element inside the selected row for a specific column. Specifically, I want to get the Text Field in the first column for the selected row.
I have an outlet to the table view and I have the index of the selected row so far, but that's about it:
- (void)getSelectedTextField
{
NSInteger selected = [tableView selectedRow];
}
Any ideas on how I can go about tackling this problem?
Edit: This is what I am trying to do: I want to change the text field to be in an editing state and focus on it so the user can start editing the text field value as soon as it is selected
I seemed to have solved my own problem:
- (void)getSelectedTextField
{
NSInteger selected = [tableView selectedRow];
// Get row at specified index
NSTableCellView *selectedRow = [tableView viewAtColumn:0 row:selected makeIfNecessary:YES];
// Get row's text field
NSTextField *selectedRowTextField = [selectedRow textField];
// Focus on text field to make it auto-editable
[[self window] makeFirstResponder:selectedRowTextField];
// Set the keyboard carat to the beginning of the text field
[[selectedRowTextField currentEditor] setSelectedRange:NSMakeRange(0, 0)];
}
Use can get all element of table view cell by get its subview. Suggest show log list subview before use it
NSInteger index = [self.tableViewFiles selectedRow];
// Get row at specified index of column 0 ( We just have 1 column)
NSTableCellView *cellView = [self.tableViewFiles viewAtColumn:0 row:index makeIfNecessary:YES];
// Get row's checkBox ( at index 0, textFields is 1,2)
NSButton *checkBox = [[cellView subviews] objectAtIndex:0];
If the text field is the only subview of your table view cell, you can get a reference to it with the following code, and select its text, so it's ready for editing:
-(void)tableViewSelectionDidChange:(NSNotification *)notification {
NSInteger row = [notification.object selectedRow];
NSTextField *tf = [[[notification.object viewAtColumn:0 row:row makeIfNecessary:NO]subviews] lastObject];
[tf selectText:tf.stringValue];
}

UITableView: load all cells

Is it possible to load all cells of an UITableView when the view is loaded so that they are not loaded when I'm scrolling?
(I would show a loading screen while doing this)
Please, it's the only way at my project (sorry too complicate to explain why ^^)
EDIT:
Okay let me explain you, what I'm definite doing:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:#"Identifier %i/%i", indexPath.row, indexPath.section];
CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSDictionary *currentReading;
if (cell == nil)
{
cell = [[[CustomTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
UILabel *label;
UIView *separator;
if(indexPath.row == 0)
{
// Here I'm creating the title bar of my "table" for each section
}
else
{
int iPr = 1;
do
{
currentReading = [listData objectAtIndex:iPr-1];
iPr++;
} while (![[currentReading valueForKey:#"DeviceNo"] isEqualToString:[devicesArr objectAtIndex:indexPath.section]] ||
[readingresultsArr containsObject:[currentReading valueForKey:#"ReadingResultId"]]);
[readingresultsArr addObject:[currentReading valueForKey:#"ReadingResultId"]];
//
// ...
//
}
}
return cell;
}
My error happens in the do-while-loop:
"listData" is an array with multiple dictionaries in it.
My problem ist that when I’m scrolling my table slowly down, all is fine, but when I’m scrolling quickly to the end of the view and then I’m scrolling to the middle, I get the error that iPr is out of the array’s range. So the problem is, that the last row of the first section has already been added to the "readingresultsArr", but has not been loaded or wants to be loaded again.
That’s the reason why I want to load all cells at once.
You can cause all of the cells to be pre-allocated simply by calling:
[self tableView: self.tableView cellForRowAtIndexPath: indexPath];
for every row in your table. Put the above line in an appropriate for-loop and execute this code in viewDidAppear.
The problem however is that the tableView will not retain all of these cells. It will discard them when they are not needed.
You can get around that problem by adding an NSMutableArray to your UIViewController and then cache all the cells as they are created in cellForRowAtIndexPath. If there are dynamic updates (insertions/deletions) to your table over its lifetime, you will have to update the cache array as well.
put a uitableview on a uiscrollview
for example , you expect the height of the full list uitableview is 1000
then set the uiscrollview contentsize is 320X1000
and set the uitableview height is 1000
then all cell load their content even not visible in screen
In my case it was that I used automaticDimension for cells height and put estimatedRowHeight to small that is why tableview loaded all cells.
Some of the answers here and here suggest using automaticDimension for cells height and put mytable.estimatedRowHeight to a very low value (such as 1).
Starting with iOS 15 this approach seems not to work anymore. Hence, another way to achieve the table to "load" all cells could be by automatically scrolling to the last cell. Depending on the tables height and how many rows it can show some cells are discarded but each cell would be loaded and shown at least once.
mytable.scrollEnabled = YES;
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:cellCount - 1 inSection:0];
[mytable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
mytable.scrollEnabled = NO;
If you want to scroll up again just scroll to the top as outlined here.
Following the comment that was made by juancazalla, I found that if you have a tableView that is using automaticDimension, loading all the cells at once can be best achieved by setting estimatedRowHeight to a low value (such as 1).

How does manually assigning tableView.rowheight affect subviews of the given Table View?

I have a custom view for displaying application status messages that I slide over my table view as needed. This worked fine until I started customizing my table view cells.
When I manually assign a row height to my table view cells in initWithSTyle...
self.TableView.rowHeight = 64.0;
...the custom view doesn't show up anymore.
I replaced the code above with a delegate method...
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 64.0;
}
...and now the custom view works as before.
Set rowHeight in the view controller.
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.rowHeight = 64.0f;
}
I think initWithStyle is too early to set the height. Eitherway, since your height is constant, it's still more efficient to set the height once (in viewDidLoad) than set it every time for each cell created (in initWithStyle or heightForRowAtIndexPath).
Did you create a custom cell class inheriting UITableVIewCell , if yes , then the height of customcell is different than the height of default cell.So you need to change the height of row to match your customcell;s in order for it to desplay correctly,Else cellswill overlap.
To Dynamically set height accoring to your customcell:-
YourCustomCell *cell = (YourCustomCell *)[tableView cellForRowAtIndexPath:indexPath];
return [cell.frame.size.height];
maintableView = [[UITableView alloc] init];
maintableView.frame = CGRectMake(0, 0, 320, 480);
maintableView.rowHeight = 100.0;
maintableView.delegate=self;
maintableView.dataSource=self;
It is working in my Xcode. Try like it. I think it will work.

Retrieving cell contents from NSOutlineView

I have an odd issue cropping up with an NSOutlineView. The view is essentially a list of apps with associated files as children. I populate the view by hand in it's data source and all of that works fine. What I now want to do is have a button to remove an item. In order to do it I implemented a method, removeAppOrFile, like so:
- (IBAction)removeAppOrFile:(id)sender
{
NSInteger selectedRow = [myView selectedRow];
if (selectedRow == -1) //ie. nothing's selected
{
return;
}
NSTableColumn *col = [myView tableColumnWithIdentifier:#"Column 1"];
NSCell *cell = [col dataCellForRow:selectedRow];
NSString *item = [cell stringValue];
NSLog(#"The row is: %ld\nThe column is: %#\nThe cell is: %#\nThe selected item is: %#",selectedRow, col, cell, item); // For testing purposes
}
myView is an IBOutlet connected to my NSOutlineView.
If I select a different row and click the button the value for selectedRow will change properly, but the NSCell object never changes, and what should be it's value (ie. NSString item) always shows that of the last visible item (ie. if there's an item with children as the last item NSString item will be the parent if it's not expanded, or the last child if it is expanded).
The weird thing is that I use basically the same code elsewhere for a doubleAction on an NSOutlineView and it works perfectly. In that case, the code is as below:
- (void)editedAppOrFile:(id)sender
{
NSInteger rowNumber = [sender clickedRow];
NSTableColumn *col = [sender tableColumnWithIdentifier:#"Column 1"];
NSCell *cell = [col dataCellForRow:rowNumber];
NSString *item = [cell stringValue];
NSLog(#"The row is: %ld\nThe column is: %#\nThe cell is: %#\nThe selected item is: %#",selectedRow, col, cell, item); // For testing purposes
}
In this case sender is the outlineView. item & cell change with rowNumber change.
Any idea as to why it's not working in the first example?
There are a few issues with your approach.
You're getting the data cell, not the -preparedCellAtColumn:row:, so you have no guarantees about what its internal object value will be.
You can ask the outline view directly for -itemAtRow:.
If you're trying to remove (in the first case) or edit (the second case), you really only need to modify your data source and then note number of rows changed (first case) or reload data for row (second case).

UITableView scrollToRowAtIndexPath not working for last 4

I am in a UITableViewController and I have textfields inside cells. When the user clicks on the textfield, I implement the UITextFieldDelegate and in method textFieldDidBeganEditing I determine the index of the cell and scroll to that position. It works perfectly for all cells expect for the last 4-5 cells. What am I doing wrong? Thanks.
scrollToRowAtIndexPath: method scrolls the cell to UITableViewScrollPositionTop or UITableViewScrollPositionMiddle only if the tableView's contentSize is large enough to bring the cell to those positions. If the cell you are trying to scroll to top or middle is the last cell or among the last few cells, it can not be scrolled to middle or top. In these situations you need to calculate the contentOffset manually for those cells.
Edit - Calculating the contentOffset:
In order to calculate the contentOffset use the method as specified by #Schoob. Put the following code in your textFieldDidBeginEditing method.
CGPoint origin = textField.frame.origin;
CGPoint point = [textField.superview convertPoint:origin toView:self.tableView];
float navBarHeight = self.navigationController.navigationBar.frame.size.height;
CGPoint offset = tableView.contentOffset;
// Adjust the below value as you need
offset.y += (point.y - navBarHeight);
[tableView setContentOffset:o animated:YES];
I found the key to using scrollToRowAtIndexPath was to make sure to call this after the view has been presented. I.e. pushed on to a navigationcontroller or presented modally.
My working code goes like this
Calling code
MyViewController *cont = [[MyViewController alloc] initWithMedication:medication];
cont.sectionToShow = 1;
[self.navigationController pushViewController:cont animated:YES];
[cont release];
Viewcontroller code inside viewWillAppear
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:self.sectionToShow];
[cont.tableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
If I did it any other way there were always edge cases where it didn't work. I guess we want to scroll late in the presentation cycle.
This is what you should be using when trying to determine the indexPath of a view/textField added on a UITableViewCell
CGPoint point = [textField.superview convertPoint:textField.frame.origin toView:self.tableView];
Then use point with
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];