UITableView scrolls bounces back to top - ios

I've been to a lot different questions on StackOverflow, But I just can't figure what is wrong here.
I have a view controller that receives data from a JSON, creating an array, and, then, it builds an UITableView, with fixed heights.
The issue is that I can't scroll to the bottom. It just bounces back.
- (UITableViewCell* )tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"SettingsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
[cell.detailTextLabel setNumberOfLines:2];
NSDictionary* place = [_placesData objectAtIndex:indexPath.row];
[cell.textLabel setText:[place valueForKey:#"nome"]];
[cell.detailTextLabel setText:[place valueForKey:#"endereco"]];
[cell.detailTextLabel setLineBreakMode:NSLineBreakByWordWrapping];
[cell.detailTextLabel sizeToFit];
UIImage* originalImage = [UIImage imageNamed:#"encontre.png"];
UIImage* resized = [UIImage imageWithCGImage:[originalImage CGImage]scale:(originalImage.scale * 1.8) orientation:(originalImage.imageOrientation)];
cell.imageView.image=resized;
cell.textLabel.font = [UIFont fontWithName:#"GillSans" size:17];
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.font = [UIFont fontWithName:#"GillSans-Light" size:17];
self.tableView.scrollEnabled=YES;
self.tableView.bounces=YES;
[self.tableView setAlwaysBounceVertical:YES];
return cell;
}
I have no idea on what else to do. Already tried to set the contentSize.height manually, force bounces and scrollEnabled on almost evert piece of code on the view controller.
Regards.

The way UITableView works is that it requires to know each row height in order to be able to compute its size.
The default behavior is to assume each row height is 44px. Which was clearly not your case here as you said it was 70px. That's why you had to change it in order to be able to scroll all way down
For instance let's say you had 10 rows. With default row height your table view was only able to scroll down to 10*44 = 440px thus the bouncing effect you got.
By setting the row height to 70px your tableview now goes down to 10*70 = 700px

can you check in the xib of your ViewController, select your tableView and click "size inspecto" in the right menu and you change in "iOS 6/7 Deltas":
you can tape -20 in height
i think the problem is in adaptation with ios7 and 6

I just had the same problem.
My solution was to update the contentSize before reloading the table's data.
tableViewOffre.contentSize = CGSizeMake(tableViewOffre.frame.size.width, [app.offres count] * 105);
Where 105 is my row height.
I think it isn't the best way to solve the problem (pretty dirty way I guess) but it's the only solution found.

Try implementing the UITableViewDelegate method tableView: heightForRowAtIndexPath:, don't let it get assigned automatically (i.e. sizeToFit). UITableView can be very unpredictable if you are not very specific and if you don't override certain methods.I had a unique problem with tableView scrolling back up to top automatically after I called [tableView reloadData]; This problem was unique because it only happened on iPad mini and iOS 8, every other device and OS was working properly. Hope it helps someone...

Actually your problem is related to frame of the table. by setting "Row height" is working for you because by chance count of row in your table and row height giving a table height that is suitable to you. But its not the right way of doing this.
Somewhere you need to check height of the table may be something like
Blockquote
(nameArray.count<10?kSACellHeight*nameArray.count:kSACellHeight*11))

Just managed to solve it, if anyone is having this same issue.
What I did is, inside the size inspector for my UiTableView, I manually set "Row Height" at 70 (the exact size I'm using).
After this, everything worked as a charm. But, if anyone can give a comprehensive explanation on what is really happening in here, it would be really great.

I've met with same issue.In my situation,I drag a tableview to a custom view controller,which is presented by a push segue.If the amount of data showed in tableview exceeds some number,then I can't touch the cell on bottom of the tableview.
Many ways have been tried:set the frame/content size of the table view,and none works for me.Finally,I find the root cause and solve it in a simple way(although not gracefully).
First,the root cause:the table view created by IB has a width larger then the its parent view controller.Thus,any cell out of view's bound will not be touched.
So,the solution is simple:Go to StoryBoard,adjust the width of table view,making it smaller than the width of parent view.It seems that if one table view is created by StoryBoard,you can't change its frame by code.That's what I've found up to now. I guess it's a bug of StoryBoard.
Help it be useful for other guys.

Keep in mind, my solution uses constraints. I ran across this issue while making a UITableView that can have a dynamic number of cells expand with more details. Here was my structure:
UIView
UIStackView
UIView (My Tabs Segue View)
UIView (My First Tab View)
UITableView (My Table I Wanted to be Scrolled)
UIView (My View if that Table was Empty)
UIView (My Second Tab View)
UITableView (My Second Table I Wanted to be Scrolled)
UIView (My View if that Table was Empty)
So, what I found out was that when I was setting the height constraint of the tables to the contentSize of the tables themselves. This originally helped account for the expandable part of the cell. But, if you want a table to be scrollable, you need to have its height shorter than its content height. By making it shorter (and having all the xib checkboxes checked as mentioned in other posts), it will automatically scroll. Granted, you can set its height via constraint or any way you want, just make sure its not the same as its content height!

Related

UITableView static cell's number of row is changed

I make one UITableView Controller had static cell. And I set number of rows 3 in Storyboard. But rows does not set 3, just be made more and more like this screen shot. I don't touch any programatic code. Did I have to make it programmatically?
That's the normal behavior of a UITableView. Even though you only have 3 rows, the view itself extends to the bottom, and it shows where the cells would be if you had data in them. To fix, do one of two things: customize the UITableView so the dividing line between cells is invisible [UIColor clearColor], or change the size of the UITableView's height depending on how many cells you have.
If you add a footerView to the UITableView then it will not extend all the way to the bottom.
I solve this problem on the story board.
Create one more cell. if you want 3cells, then make 4cells.
Make whatever you want on cell. put the UIButton or UILabel any way. But except 4th cell.
Expend your 4th cell's height, to the bottom.
And finally, check hidden in attributes inspector. It makes 4th cell hidden.
That's it!
And I add one image file. I hope it help your work. Thanks.
Simple solution is to set footer's frame to nil:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/*........*/
tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
return cell;
}
I would use a regular View Controller and insert a TableView of the required table height.
Then if you really want to you can do stuff with the cell height and label sizes.

How to draw connecting lines between two uitableviewcells ios

I want to show links between two cells of uiTableView.
For Ex:
To show links between cells 1 and 5, it could be shown like:
Does any one has any idea how this can be achieved. Also when table scrolls, these links should be scrolled with it.
This looks like you want to build hierarchical view. Your implementation might be rejected by Apple due to not taking HIG into account.
Also what will be in case when lower part is not seen to user? Arrow with no end and need to scroll down for the user?
You might want to do a tree like structure (anything hierarchical) instead of ugly (sorry for that) arrows.
If you want arrow between two cell then make a separate UIView class for the Tablecell, in that UIView add one UILabel for text and one UIImageView for arrow, adjust there position as per your requirement.
Now pass this UIView to cell.
Hope this will help you.
UITableViewCell is just a subclass of UIView and UITableView is a subclass of UIScrollView. The only fanciness that UITableView provides is creating/reusing the cells and laying them out in the scroll view. (That's a gross over-simplification but for this It'll do the trick.)
So if I have a UIView subclass that draws an arrow, then it's just a matter of getting the frame for the cells I want to point to. CGRect frame1 = [[self.tableView cellForRowAtIndexPath:indexPath] frame];
Some pseudocode...
topCellFrame = get top cell frame;
bottomCellFrame = get bottom cell frame;
arrow = new arrow view;
arrow set frame = frame with origin of top cell frame origin, and height of distance from topCellFrame to bottomCellFrame;
tableView add subview = arrow;
There are edge cases to think about, If the top cell or bottom cell are offscreen the cellForRowAtIndexPath: will return nil and frame will be CGRectZero.
But I'll leave that as an exercise for you.
Edit: (I haven't done this exact thing, but I have done some similar things with the frames of cells)

Prevent UITableViewCells from creating as you scroll down

I'm creating a mail screen using which visually resembles the iOS native email app. It looks like this (Both images are of the same screen. First one is the top half and the second one is the rest of it).
The difference is my mail screen has more custom fields in addition to normal To, Cc, Subjet fields.
I'm using a UITableViewController to create this. Below is a code snippet which creates a cell (For each cell it's pretty much the same).
- (UITableViewCell *)tokenTableView:(TITokenTableViewController *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
self.tableView.frame = CGRectMake(0,0,320,320);
UIView *contentSubview = nil;
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifierSubject];
if(!self.txtSubject) {
self.txtSubject = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
self.txtSubject.frame = CGRectMake(10, cell.frame.size.height / 2 - self.txtSubject.font.lineHeight / 2, tableView.tableView.bounds.size.width, 30);
self.txtSubject.placeholder = #"Subject";
[self setupMailData:indexPath.row];
}
contentSubview = self.txtSubject;
}
Say, I open up a draft. All the details in the input fields are filled and without changing anything, I hit send and it crashes the app. I know what's causing this. The problem is that normally the cells that are under the viewable portion of the screen gets created as you scroll down, right? But in this scenario, if I send it without scrolling down but those cells below the viewport don't exist thus it throws the error.
If I open the draft, scroll down and hit send, it works fine.
I need to know if there's a way to create all these cells at once. Even the cells that are below the viewport at first. Not depending on the user to scroll down.
I hope you have an idea about my situation. Can anyone suggest a solution?
Thank you.
follow steps:
Take uiscrollview and set scrollview frame as which you want to display.
Take uitableview as a subview of uiscrollview
set property Scrolling Enabled = NO (uncheck checkbox in .xib) of uitableview
call reloaddata method of uitableview
set tableview frame and contentsize of scrollview
tblEmail.frame = CGRectMake(yourXPos, yourYPos, yourWidth, tblEmail.contentSize.height);
scrollObj.contentSize = CGSizeMake(yourScrollWidth,tblEmail.contentSize.height+10);
so, the height of tableview is equal its contentsize. so, its create all cells at a time. and set contentsize of scrollview is equal tableview contentsize. so, the scrolling feature is worked like uitableview scrolling...
Use a Storyboard, add a UITableViewController and set the 'Content' to StaticCells.
Then you can define all the cells and their content in the Storyboard. You can even wire stuff up to IBOutlets in your UITableViewController subclass and they will all be there for you when viewDidLoad is fired ...
When using a Storyboard your code for getting the ViewController looks like:
[[UIStoryboard storyboardWithName:#"MyStoryboard" bundle:nil] instantiateInitialViewController];

UICollectionView's cell disappearing

What's happening
Currently I have an application that uses two UICollectionViews inside a UITableView. This way I create a Pulse News look like application. My problem with this is that sometimes the 6th and 11th row disappears completely, leaving a blank space where it should be the cell. I wouldn't actually mind, if all the cells were like this (and this way I could assume that I wasn't doing things correctly), but the thing is, is just happening with those specific ones.
My theory
The 6th and 11th rows are the ones that appears when I start scrolling, so by default I am able to see 5 cells, and when I do the first horizontal scrolling the 6th comes up (blank space sometimes).
What I have
The only thing I am doing at the moment is this:
[self.collectionView registerNib:[UINib nibWithNibName:CELL_NIB_NAME bundle:nil] forCellWithReuseIdentifier:CELL_IDENTIFIER];
On the viewDidLoad. And on the creation of the cell:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_IDENTIFIER forIndexPath:indexPath];
NSMutableDictionary *dictionary = [self.DataSource objectAtIndex:[indexPath row]];
[cell buildViewWithDictionary:dictionary withReferenceParent:self.referenceViewController];
return cell;
}
So on my understating nothing fancy going on here. I though there was something wrong on the data source (a dummy JSON file), but sometimes it works ok and the cell shows, so I guess from that part is ok.
So my "question": Does anyone knows what's going on? I don't really like to say that it's a bug from iOS, but I can't think of anything else.
Edit 1.0
The amazing part is that this method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
Is going from indexPath [0,4] to [0,6] without calculating the [0,5]. First time I actually see this happening in iOS.
Edit 2.0
I have switched the way I am creating the cells, and instead of dequeuing I am using the old way:
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CELL_NIB_NAME owner:self options:nil];
MyCell *cell = (MyCell *)[nib objectAtIndex:0];
Still the same sad result.
So, what did work?
1) Subclass UICollectionViewFlowLayout.
2) Set the flowLayout of my UICollectionView to my new subclass.
3) On the init method of the UICollectionViewFlowLayout subclass, set the orientation you want:
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
In my case it is Horizontal.
4) The important part:
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
At this moment, I should theorise a bit, but honestly I don't have a clue.
The above answers didn't work for me, but after downloading the images, I replaced the code
[self.myCollectionView reloadData]
with
[self.myCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
to refresh the collectionview and it shows all cells, you can try it.
None of the solutions given by anyone helped me in my custom layout that we need to have in our app.
Instead, I had to do this: (And yeah, IT WORKS!!!)
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
CGSize size = [self collectionViewContentSize];
rect.size.height = size.height*2;
NSArray *atrributes_Super = [super layoutAttributesForElementsInRect:rect];
return atrributes_Super;
}
After all, UICollectionView is just looking for the attributes for the elements to be displayed in your screen's rect.
Rob's tip about the bug helped me. The bug states that if the section insets and cells widths and spacing add up exactly to the width of the screen then the first column sometimes randomly dissappears and reappears for some cells in some places. Rather than subclass or change the cell widths, I changed the section insets for left and right in my storyboard from 6 to 4 and it I haven't seen the problem again.
As I run the same problem suddenly and spent some time figuring out one of possible reasons of cell disappearing during the scroll, I will add my answer as well.
Prerequisites of the problem:
You have a UICollectionView instance
You have a UICollectionViewFlowLayoutSubclass
The problem
Cells disappear from the Collection View after scrolling to the certain point.
The source of the problem is in wrong subclassing of the UICollectionViewFlowLayout.
As it explicitly said in documentation:
Every layout object should implement the following methods:
- collectionViewContentSize
- layoutAttributesForElements(in:)
- layoutAttributesForItem(at:)
- layoutAttributesForSupplementaryView(ofKind:at:) // (if your layout supports -supplementary views)
-layoutAttributesForDecorationView(ofKind:at:) // (if your layout supports decoration views)
- shouldInvalidateLayout(forBoundsChange:)
By relying on UICollectionViewFlowLayout implementation of methods above we miss the fact, that func layoutAttributesForElements(in rect: CGRect) and collectionViewContentSize will generate wrong contentSize (the size that would be correct if all the cells would have itemSize size and the content size would be corresponding. As soon as scroll offsetY will be greater that contentSize height cell will all disappear.
The solution
The solution is in proper UICollectionViewFlowLayout subclassing. Override all the methods that are required to override and everything will work just fine.
In my case (vertical scroll, with cells disappearing in first view), cells were disappearing due to incorrect estimated size. It seems, UICollectionView uses the estimated size to calculate the items to load in first view. I'd set the estimated size too high which was resulting in wrong calculations for number of items to load in first screen.
The moment I made the estimated height bit low, all the cells appeared correctly.
We ran into disappearing cells recently and found that rather than skipping 'hidden' cells we were accidentally inserting 0x0 sized cells. The resulting behavior was very confusing and did not suggest these invisible cells were the issue. We would see the correctly sized cells and layout, but a few of the valid cells would consistently disappear after scrolling off/on screen. I have no idea why intermingling 0 sized cells would cause this behavior, but removing them fixed the problem. This may not be causing your problem, but this may be helpful to devs searching for similar symptoms.
Just ran into an issue where all UICollectionView cells were disappearing on scroll.
This happened because I had declared
extension UICollectionViewLayout {
static let defaultLayout: UICollectionViewLayout {
let layout = UICollectionViewFlowLayout()
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
return layout
}()
}
... meaning the same layout instance was being used in multiple UICollectionViews. I had meant to make that a computed var. Hope this helps someone who's accidentally using the same layout object in multiple collection views.
What caused the cells to disappear in my case was that the data source was being deallocated prematurely. UICollectionView.dataSource is a weak property, which means that unless you keep a strong reference to it, the object will be deallocated at the end of the scope in which you created. The problem manifested itself with disappearing cells as soon as I tapped on the UICollectionView.
For me this issue seemed to be related with the way i make my collectionview adapt to an open keyboard to prevent content overlaps.
in my observer to respond to KeyboardWillShow i had this:
var userInfo = obj.UserInfo[UIKeyboard.FrameEndUserInfoKey];
if (userInfo is NSValue value)
{
var rect = value.CGRectValue;
var windowOffset = this.Superview.ConvertPointToView(this.Frame.Location, UIApplication.SharedApplication.KeyWindow);
var newHeight = rect.Y - windowOffset.Y;
this._controller.CollectionView.Frame = new CGRect(0, 0, this._controller.CollectionView.Frame.Width, newHeight);
}
After changing it to this:
var userInfo = obj.UserInfo[UIKeyboard.FrameBeginUserInfoKey];
if (userInfo is NSValue value)
{
var rect = value.CGRectValue;
UIEdgeInsets contentInsets = new UIEdgeInsets(0, 0, rect.Height, 0);
this._controller.CollectionView.ContentInset = contentInsets;
this._controller.CollectionView.ScrollIndicatorInsets = contentInsets;
}
The cell disappearance issue completely went away. This is C# from working with xamarin but i hope it helps someone else.
I think this is not a UICollectionView‘s bug, maybe your not return right data in - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect method.
You can see this demo: https://github.com/lqcjdx/YLTagsChooser , all cells can appear when scolling the UICollectionView.

Avoid auto resize of uitableview cell content view on entering edit mode

I have a uitableviewcell with content view containing some custom view.'
When the table view enters edit mode the content view resizes (becomes narrower) there by the image in the content view is shrunk horizontally
Does anyone know how to prevent this ?
I have set the cell indentation to none.
Thanks
Have you tried setting shouldIndentWhileEditing to NO
Take a look at properties :
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html
Have you tried setting the auto-resize masks on the view?
theView.autoresizingMask = UIViewAutoresizingNone;
You may need to set it on the content view and/or the image view - it's not clear exactly how your view hierarchy is structured. However, the frame might be set explicitly (rather than auto-resized) by the framework, in which case this won't work.
If you are trying to have a background image for the entire table cell, you may also want to try an alternative method which is to set the backgroundColor of the cell like this:
UIImage* someImage = [UIImage imageNamed:#"someImage"];
cell.backgroundColor = [UIColor colorWithPatternImage:someImage];
Remember to make sure the backgroundColor of all other views you place inside are [UIColor clearColor] so that you can see through to the background image.
You can always get a tableviewcell with an indexpath. Using that tableviewcell reuseidentifier, You can avoid the tableview cell content size to be resized or not. I had a requirement to implement the similar kind of functionality to avoid resizing of seperate cells. PFB the code.
-(BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
BOOL shouldIndentWhileEditingRow = NO;
UITableViewCell *lTableViewCell = [tableView cellForRowAtIndexPath:indexPath];
/*Change the position of the target rect based on Sending messages or Receiving messages*/
if ([lTableViewCell.reuseIdentifier isEqualToString:#"SendingChatCellIdentifier"]) {
shouldIndentWhileEditingRow = NO;
}else if ([lTableViewCell.reuseIdentifier isEqualToString:#"ReceivingChatCellIdentifier"]){
shouldIndentWhileEditingRow = YES;
}
return shouldIndentWhileEditingRow;
}
I did something similar to avoid the cell content to be resized when using cell automatic dimension.
My problem was that the textView inside the cell, after the selection, was wrapping its content in more lines, and I just wanted to avoid this.
To solve this "issue":
I added a trailing constraint of 40px (the size of the accessory view) to the cell content
On cell select, i change the constraint to 0, so the text is 40 px larger, but as the accessory shows up, you don't see any changes.
The pro of this solution is that the content dimension is not changing anymore when user select a row.
the con is that you have always 40px of free space on the right of the cell, also when not selected.

Resources