scrollToRowAtIndexPath is not working fine? - ios

I am using a tableview with autolayet corners set to (0,0,0,0).I had a custom cell set on the table view.my issue is the scrollToRowAtIndexPath is not working fine.my cellForRowAtIndexPath methods is looking like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
RTableViewCell *cell = (RTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil)
{
for (UIView *currentView in tableView.subviews) {
if ([currentView isKindOfClass:[UIScrollView class]]) {
((UIScrollView *)currentView).delaysContentTouches = NO;
break;
}
}
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor =[UIColor colorWithRed:216/255.0 green:231/255.0 blue:244/255.0 alpha:1.0];
cell.selectedBackgroundView = myBackView;
return cell;
}
i had dynamic number of sections and dynamic number of rows inside that.
and in my viewDidAppear i am calling like this
dispatch_async(dispatch_get_main_queue(), ^{
//int indexValue = (int)[sections indexOfObject:string];
[rtable reloaddata];
NSIndexPath *rowIndexPath = [NSIndexPath indexPathForRow:0 inSection:6];
[self.rtable scrollToRowAtIndexPath:rowIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
});
anybody knows where i am going wrong?

Try below code in viewWillAppear or viewDidLayoutSubviews:
[rtable reloaddata];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSIndexPath *rowIndexPath = [NSIndexPath indexPathForRow:0 inSection:6];
[self.rtable scrollToRowAtIndexPath:rowIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
});

Related

Insert UITableViewCell With Animation and Scroll to it

My requirement is simple , i just need to add a TableCell with rightRowAnimation and scroll to it. It happens as long as i am with within tableView height , as i cross the height of tableView to add cell further , it adds cell but displays no animation when scrolling to it.
Attached is a simple project with a UITableView for reference , Appreciate your help !!
Sample Project with a simple UItableView and Add Button
Code
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell1"];
BOOL myBool = indexPath.row%2 == 0;
if(myBool){
cell.backgroundColor = [UIColor redColor];
}else{
cell.backgroundColor = [UIColor whiteColor];
}
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
return cell;
}
-(IBAction)addTapped:(id)sender {
[self.dataArray addObject:#"New Object"];
// [_tableView beginUpdates];
[_tableView insertRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
// [_tableView endUpdates];
[_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
Use bellow method for the animation.
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.alpha = 0;
cell.layer.transform = CATransform3DMakeScale(0.5, 0.5, 0.5);
[UIView animateWithDuration:0.7 animations:^{
cell.alpha = 1;
cell.layer.transform = CATransform3DScale(CATransform3DIdentity, 1, 1, 1);
}];
}
change what ever your requirements
you can try this to animate row put in table.
-(void)viewWillAppear:(BOOL)animated
{
dispatch_async(dispatch_get_main_queue(), ^{
[UIView transitionWithView:yourtablename
duration:5.1f
options:UIViewAnimationOptionTransitionFlipFromTop
animations:^(void) {
[yourtablename reloadData];
} completion:NULL];
});
}
also you can change animation style.

insertRowsAtIndexPaths or reloadData doesn't respond

Here is my code. And yesterday it works just fine. But this morning, it doesn't work.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
RSDrug *drug = [[RSDrug alloc]init];
[drugArray insertObject:drug atIndex:0];
NSIndexPath *ip = [NSIndexPath indexPathForRow:1 inSection:0];
[tableView insertRowsAtIndexPaths:#[ip] withRowAnimation:UITableViewRowAnimationAutomatic];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return drugArray.count + 1;
}
I have tried to add some code like beginUpdates/endUpdates, or I delete insertRowsAtIndexPaths, just use reloadData.
But same result. When the app runs to insertRowsAtIndexPaths or reloadData, it stuck, no response.
So I need some help. How to solve this?
Found the problem..........A stupid mistake
There are two UITextFields in the added cell, and they all have the same leftView, my code is like this:
UIImageView *leftImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"img"]];
field_1.leftView = leftImage;
field_2.leftView = leftImage;
I never know that I can't reuse the leftView. If I set the leftImage to field1, I can't set it to field2 anymore.
When I changed to this, it works again.
field_1.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"img"]];
field_2.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"img"]];
Try this sequence...
NSMutableArray *indexPaths=[[NSMutableArray alloc]init];
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tableView beginUpdates];
RSDrug *drug = [[RSDrug alloc]init];
[drugArray insertObject:drug atIndex:0];
if (indexPath.row == 0) {
[indexPaths removeAllObjects];
[indexPaths addObject:[NSIndexPath indexPathForRow:indexPath.row++ inSection:0]]; // here inserting row index=1;
[tableViewMenuList insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
}
[tableView endUpdates];
}
Have you tried this?
RSDrug *drug = [[RSDrug alloc]init];
[drugArray insertObject:drug atIndex:0];
[tableView beginUpdates];
// indexpath inserted is with the index 0 same with the `insertObject: `
NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView insertRowsAtIndexPaths:#[ip] withRowAnimation:UITableViewRowAnimationAutomatic];
//here is what i use to do instead of #[]
//[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:ip] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
EDIT
Your code are working fine. i tested it. here..
Code:
Output:
Log:
Check the tested code above if you have omitted something.
I think the problem is the delegates of your table, make sure that your table have the delegate for both UITableViewDataSource & UITableViewDelegate.
Hope this is helpful.. Cheers.. :)

Delete selected Items in collection view

I select 5 items in my collection view and i want to delete it. Please help me delete the selected items. I put one button and when i press that button all selected items are delete that i want. My button click code.
- (IBAction)btn_delete:(id)sender {
NSArray *selectedItemsIndexPaths = [self.MyCollectionView indexPathsForSelectedItems];
NSLog(#"Selected images: %#",mySelectedArray);
[self.MyCollectionView deleteItemsAtIndexPaths:selectedItemsIndexPaths];
[self.MyCollectionView reloadData];
}
First remove Objects for DataSource, then try delete cells from Collectionview
-(void)deleteCellInCollectionViewAtIndex:(int)index{
if (self.collectionView) {
[self.collectionView performBatchUpdates:^{
NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:index inSection:0] ;
[self.collectionView deleteItemsAtIndexPaths:#[cellIndexPath]];
} completion:nil];
}
}
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#pragma Mark For Collection View Methods
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [patternImageArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"Cell";
PatternViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
NSString *myPatternString = [patternImageArray objectAtIndex:indexPath.row];
cell.ImageView.image = [UIImage imageNamed:myPatternString];
cell.ImageLabel.text = myPatternString;
ind = indexPath.row;
return cell; }
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
PatternViewCell *mySelectedCell = (PatternViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
mySelectedCell.ImageLabel.backgroundColor = [UIColor blueColor];
mySelectedCell.ImageLabel.textColor = [UIColor whiteColor];
[mySelectedArray addObject:indexPath];
i = indexPath.row; }
- (void)viewDidLoad {
[super viewDidLoad];
patternImageArray = [[NSMutableArray alloc]initWithObjects:#"Thar.jpg",#"Thar1.jpg",#"Thar2.jpg",#"Thar3.jpg",#"Thar4.jpg",#"Thar5.jpg",#"Thar6.jpg",#"Thar7.jpg",#"Thar8.jpg", nil];
self.MyCollectionView.multipleTouchEnabled = YES;
mySelectedArray = [[NSMutableArray alloc]init]; }
- (IBAction)btn_delete:(id)sender
{
[self.MyCollectionView reloadData];
NSLog(#"Selected images: %#",mySelectedArray);
}
#end
In your btn_delete: method, add this code
NSArray *selectedItemsIndexPaths = [self.MyCollectionView indexPathsForSelectedItems];
NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
for (NSInteger counter = 0; counter < [mySelectedArray count]; counter++) {
NSIndexPath *indexPath = mySelectedArray[counter];
[indexSet addIndex:indexPath.row];
}
[patternImageArray removeObjectsAtIndexes:indexSet];
[self.collectionView performBatchUpdates:^{
[self.collectionView deleteItemsAtIndexPaths:mySelectedArray];
} completion:^(BOOL finished) {
[mySelectedArray removeAllObjects];
}];
In your collectionView:didSelectItemAtIndexPath: method, you should first check if array already contains that indexpath before adding to array.
You can see it below:
if(![mySelectedArray containsObject:indexPath])
[mySelectedArray addObject:indexPath];

uiTableViewCell Add row with and image and remove row with second tap

I've been trying to figuered this out for hours. I'm just plain old stuck here. What im trying to accomplish is basically inserting a row directly below the row just tapped in the tableview in addition i would like to add and image to the row and and make the image clickable to respond to its click event.
So here is my code.
I implemented (i belive) the nessesary methods to handle all the actions for the uitableview.
when the user taps the cell i handle that action by executing the following code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (debug==1) {
NSLog(#"running line 225%# '%#'", self.class, NSStringFromSelector(_cmd));
}
Locations *location = nil;
Locations *tempObject = [[Locations alloc]init];
//test to see if we are looking for the search box or if we are essentially looking from the main view controller.
if (self.searchDisplayController.active) {
location= [self.searchResults objectAtIndex:indexPath.row];
NSLog(#"location : %#" ,location.locationName);
} else {
location = [self.locations objectAtIndex:indexPath.row];
NSLog(#"location : %#" ,location.locationName);
//set the new indexpath to 1 more then before so that we can essetially add a row right below the actual tapped item.
NSIndexPath *newPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
indexPath = newPath;
[self.locations insertObject:tempObject atIndex:indexPath.row ];
[tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
self.visibleCell =YES; //set this boolean variable so that we can add a specific row image to this var
// self.locations[0].isItVisible = YES;
}//ends the else statement.
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
the above code inserts an empty cell into my tableview.
however how can i set the cell so that its custom and not the same as the others. In other words my initial cells data-source are basically bound to an nsobject and a string property location-name. However when i go try to update the table cells in the above method i obviously cannot add an image into a string so I'm running in to a error.
so i tried to instead make the update on the
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
by basically checking if a variable is set to true or false but that turned out to be buggy because even when i scroll this method gets called.
How should i go about doing this. I think i have to do it all in the didselectrowindexaspath method. But i cant figured out how to change the newly inserted cell to contain an image only.
Any help would be appreciated.
EDIT
here is what im doing to try to add the image under the cellforrowindexpath method.
if(self.visibleCell==YES){
UIImage *clkImg = [UIImage imageNamed:#"alarm_clock.png"];
cell.imageView.image = clkImg;
}
Im a noob so im not sure im doing this correctly.
EDIT
this is the full cellforatindexpath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (debug==1) {
NSLog(#"running line 159 %# '%#'", self.class, NSStringFromSelector(_cmd));
}
// NSLog(#"cell for row at index path just got called");
//JAMcustomCell *myCell = [[JAMcustomCell alloc]init];
static NSString *CellIdentifier = #"ListPrototypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Locations * locations = [[Locations alloc]init];
//tableView.backgroundColor = [UIColor blackColor];
// NSLog(#"this is visible '%hhd'", locations.isItVisible);
if(self.visibleCell==YES){
UIImage *clkImg = [UIImage imageNamed:#"alarm_clock.png"];
cell.imageView.image = clkImg;
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
locations = [self.searchResults objectAtIndex:indexPath.row];
}
else{
locations = [self.locations objectAtIndex:indexPath.row];
}
cell.textLabel.text = locations.locationName;
cell.textLabel.textColor = [UIColor whiteColor];
//cell.backgroundColor =[UIColor blackColor];
// cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"Graytbl.fw.png"]];
cell.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"blueTbl.fw.png"]];
cell.selectedBackgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"blueTbl.fw.png"]];
// UIFont *myFont = [ UIFont fontWithName: #"Oswald" size: 25.0 ];
// cell.textLabel.font = myFont;
cell.textLabel.font= self.MyFont;//[UIFont fontWithName:#"Oswald-Regular.ttf" size:15];
return cell;
}
Try this approach, I used your idea of Bool
#pragma mark - Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.visibleCell){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"imageViewCell" forIndexPath:indexPath];//ListPrototypeCell
UIImageView *imageVIew = (UIImageView *)[cell viewWithTag:1];
[imageVIew setImage:[UIImage imageNamed:#"alarm_clock.png"]];
return cell;
}else{
return [tableView dequeueReusableCellWithIdentifier:#"ListPrototypeCell" forIndexPath:indexPath];
}
}
#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if(!self.visibleCell){
self.numberOfRows++;
self.visibleCell = YES;
NSIndexPath *indexPathCell = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPathCell] withRowAnimation:UITableViewRowAnimationBottom];
}else{
self.numberOfRows--;
self.visibleCell = NO;
NSIndexPath *indexPathCell = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
[self.tableView deleteRowsAtIndexPaths:#[indexPathCell] withRowAnimation:UITableViewRowAnimationTop];
}
}
I created a demo project for you.
I hope it helps

Seeing a TextField as a subview of a UICell

I have added a TextField to a UICell in order to allow a user to change the TextLabel of said cell. Everything works fine in that the keyboard appears and the TextLabel changes to the correct value when I press return. I can't, however, SEE the text as it is being edited. Here is my code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *aCategory = aCell.textLabel.text;
[[aCell detailTextLabel] setText:aCategory];
[aCell setEditing:YES animated:YES];
UITextField *userText =[[UITextField alloc] init];
userText.tag = indexPath.row;
[aCell addSubview:userText];
NSArray *test =[aCell subviews];
NSLog(#"I have %d many subviews",[test count]);
userText.alpha=1.0;
[userText setDelegate:self];
userText.autocorrectionType = UITextAutocorrectionTypeNo;
[aCell bringSubviewToFront:userText];
[userText becomeFirstResponder];
}
I would like to do it without custom cells if possible. Thanks in advance.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *aCategory = aCell.textLabel.text;
[[aCell detailTextLabel] setText:aCategory];
UITextField *userText = [[UITextField alloc] initWithFrame:aCell.textLabel.frame];
userText.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
userText.font = aCell.textLabel.font;
userText.text = aCell.textLabel.text;
aCell.textLabel.text = nil;
userText.tag = indexPath.row;
[aCell addSubview:userText];
[userText setDelegate:self];
userText.autocorrectionType = UITextAutocorrectionTypeNo;
[aCell bringSubviewToFront:userText];
[userText becomeFirstResponder];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:textField.tag inSection:0];
UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
aCell.textLabel.text = textField.text;
[textField removeFromSuperview];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}

Resources