How to programmatically select a row in a table

I have a table that the user is viewing. When the user shakes his device, I want a random row to be selected. How to do it?

I have a sign of shaking, I can create a random integer that does not exceed the number of lists, but I can not find the correct code so that this line is highlighted in the table.

In the Apple documentation, I found:

NSIndexPath *rowToSelect; // assume this exists and is set properly UITableView *myTableView; // assume this exists [myTableView selectRowAtIndexPath:rowToSelect animated:YES scrollPosition:UITableViewScrollPositionNone; [myTableView scrollToRowAtIndexPath:rowToSelect atScrollPosition:UITableViewScrollPositionNon animate:YES]; 

but I can't get it to work. I have a UITableView *myTableView . I used a randomized integer like rowToSelect.

+4
source share
2 answers

This is how I earned it. I saved the following line:

 NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:randomRij inSection:0]; 

I added the following lines:

 [eenTabelView selectRowAtIndexPath:scrollIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone]; 

I commented on the following line:

 //[[self eenTabelView] scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionNone animated:NO]; 
+5
source

An important rule: all user interface changes must be made in the main topic. Add

 if (![NSThread isMainThread]) { [self performSelectorOnMainThread:_cmd withObject:(%YOUR_OBJECT_TAKEN_IN_THIS_SELECTOR) waitUntilDone:Yes]; } 

before your code starts it already in the main thread OR (a more correct option), extract all your user interface changes into a separate method and call it in the main thread.

Example:

 -(void)yourSelector { … UI changes … } -(IBOutlet)yourAction { [self performSelectorOnMainThread:@selector(yourSelector) withObject:nil waitUntilDone:Yes]; } 
0
source

Source: https://habr.com/ru/post/1392354/


All Articles