I have a standard UINavigationController with a UITableViewController at it's root. In IB, I paint a prototype cell with a label and a UIView. The UIView contains a button. I'd like the UIView to be x-aligned after the label, as a function of the length of text in the label.
In IB, the view's left side is initially aligned with the label's left side. There are no layout constraints in IB.
Here's my cellForRowAtIndexPath ...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSArray *labels = #[#"SOME STRING", #"SHORTER", #"A VERY MUCH LONGER ONE", #"REGULAR ONE", #"TINY"];
UILabel *label = (UILabel *)[cell viewWithTag:32];
label.text = labels[indexPath.row];
UIView *view = [cell viewWithTag:33];
CGSize size = [label.text sizeWithAttributes:#{NSFontAttributeName:label.font}];
view.frame = CGRectOffset(label.frame, size.width, 0);
return cell;
}
Two problems: I've set breakpoints and watch this code running the first time the view appears. I see the view.frame get changed for each row, but the view does not change position. I remains in it's IB-position, right on top of the label. If I scroll the table down, the views on lower cells (presumably reused) are in the desired position. If I scroll back up, the upper rows are also good. It just fails to work on the initial presentation of the upper cells.
Second problem is that the button contained in only the first row has a subtle, strange effect applied to it's text, like a blur. See attached...
First Row Button (zoomed in mac preview... see that extra blur on the left edge of the letters?)
Other Row Buttons
Stuff I tried:
I've tried a few variations, including using a regular view controller with a table view added (rather than a UITableViewController). I've found that if I reloadData on viewDidAppear, that solves the placement problem, but not the blurry button. (Also, I don't like the idea of needing to reload on viewDidAppear). Doing so on viewWillAppear has no effect at all. I've also tried animating the label change slowly. It happens, but again, only on the second time the cell is configured. I try changing the UIView color to prove the code is being run. The color change happens every time, including the first time, but not the view placement. Am I nuts?
For problem 1:
Try calling [cell layoutIfNeeded] before returning the cell, there should be no performance hit when it does not need relayout.
For problem 2:
try calling CGRectIntegral before you set the frame. ie
view.frame = CGRectIntegral( CGRectOffset(label.frame, size.width, 0) );
Related
I'm trying to put some images into a UITableView, so I put an Image View into the UITableViewCell and set it aspect fit.
After starting the simulator, it appears to be right, but when I click at one cell or scroll out the originally hidden cells(may be the reused ones), the image breaks the limit of the image view's setting and destroys the layout.
the middle picture is normal, but the upper or lower one is out of shape.
cellForRowAtIndexPath function as follow:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ShangbaoOriginCell";
ShangbaoOriginCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.newsSampleLabel.text = [NSString stringWithFormat:NSLocalizedString(#"Cell %d",), indexPath.row];
cell.cellView.contentMode = UIViewContentModeScaleAspectFit;
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
cell.imageView.image = self.tableItems[indexPath.row];
return cell;
}
whether cell.imageView.contentMode is set or not, this problem exists.
I've added bg color, ImageView is black, Content View is blue, Cell is green.
So I saw incredible thing, the (table view) cells become not wide enough (you can see from the narrow gap between two pictures). Which is set properly in story board that the cell's width cover the whole screen.
I forgot to say that this table view is in a tabbed application, but I think this doesn't matter . And this time I have added constraints to the image view, but in vain.
I have a UITableViewCell that is implemented using storyboard that looks like:
Here is what the cell should look like without an image:
I have been fiddling with the constraints and banging my head trying to figure this out but have had no luck. I have a pretty good understanding of constraints and how to add them programmatically but have had no luck with this specific problem and feel like I am just adding layout constraints to the cell willy-nilly with no logical thought process. The cell represents a newsfeed post which may or may not have an image in the main image view at the top, and should behave as follows. If the cell doesn't have an image in it the bottom bar with the like and comment counts, moves up to align with the top of the cell. I achieved this behaviour by setting a constraint that kept the smaller image view, post title, post time and the post content a set distance away from the bottom of the cell. This approach works and when the cell is resized in the heightForRowAtIndexPath method the subviews move appropriately. The problem comes when the text in the post content is larger then a single line. The height of the cell adjusts correctly but the top of the text view stays at the same location and grows downward and overflows into the next cell. When I place the constraints to align the four subviews with the top of the cell I run into issues when there is no image and the post content is larger then a single line. In this case, the cell resizes to be smaller than its original size and the subviews stay at the distance specified by the constraint. The smaller image, post title, time and content are clipped and don't display. This is such an odd problem with so many different cases. I have been working at this for almost two days and could really use someone else's thoughts on how to solve this issue. I hope this isn't too confusing, thanks for the help!
I have one way to solve this, but I'm sure there are many others. I gave both image views a fixed height constraint. The small image view and the top label (Post Title) have fixed heights to the top of the cell -- both of these as well as the height constraint of the large image view have IBOutlets to them so they can be changed in code. The bottom label (Post Content) has its number of lines set to 0, and has an IBOutlet to its height constraint (all the labels had the standard 21 point height to start). In code, I check for the existence of an image at each indexPath, and change the constraints accordingly.
- (void)viewDidLoad {
UIImage *image1 = [UIImage imageNamed:#"House.tiff"];
[super viewDidLoad];
self.theData = #[#{#"pic":image1, #"post":#"short post"},#{#"post":#"short post"},#{#"pic":image1, #"post":#"Long long post with some extra stuff, and even some more"},#{#"post":#"Long long post with some extra stuff, and even some more"}];
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.theData.count;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat ivHeight = (self.theData[indexPath.row][#"pic"])? 215 : 0; // 215 is the fixed height of the large image view
CGSize labelSize = [self.theData[indexPath.row][#"post"] sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(152, CGFLOAT_MAX)];
return 140 + ivHeight + labelSize.height; // the 140 was determined empirically to get the right spacing between the 3 labels and the bottom bar
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RDCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.label.text = self.theData[indexPath.row][#"post"];
cell.iv.image = self.theData[indexPath.row][#"pic"];
if(self.theData[indexPath.row][#"pic"] == nil){
cell.heightCon.constant = 0; // heightCon is the outlet to the large image view's height constraint
cell.ivTopCon.constant = 8; // ivTopCon is the outlet to the small image view's spacing to the top of the cell
cell.labelTopCon.constant = 8; // labelTopCon is the outlet to thetop label's spacing to the top of the cell
}else{
cell.heightCon.constant = 215; // this number and the following 2 are taken from the values in IB
cell.ivTopCon.constant = 185;
cell.labelTopCon.constant = 233;
}
CGSize labelSize = [self.theData[indexPath.row][#"post"] sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(152, CGFLOAT_MAX)];
cell.labelHeightCon.constant = labelSize.height;
return cell;
}
Hey #rdelmar thanks for the solution! Eventually I ended up just designing two different cells in the storyboard file with different reuse identifiers but the same subclass. I then checked in the cellForRowAtIndexPath method if the cell had content or not, and assigned the correct identifier. If this is the incorrect way of doing this, or will cause problems down the road please let me no in the comments.
I'm having some problems implemented dynamic row heights in a UITableView - but it isn't the cells that I'm having a problem with, its the UILabel inside of the cell.
The cell just contains a UILabel to display text. My tableView:heightForRowAtIndexPath: is correctly resizing each cell by calculating the height of the label that will be in it using NSString's sizeWithFont: method.
I have a subclass of UITableViewCell that just holds the UILabel property that is hooked up in storyboard. In storyboard I've set its lines to 0 so it will use as many lines as it needs, and I've set its lineBreak to Word Wrap.
Here is how I'm setting up the cells:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ExpandCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
SomeObject *object = self.tableObjects[index.row];
cell.myLabel.text = [object cellText];
[cell.myLabel sizeToFit];
return cell;
}
When I build this, I get my table view with the cell's all sized to the correct height for their content, but the labels are all 1 line that just runs off the side of the cells. However, if I scroll the table so cell's leave the screen, and then scroll back to them, their label will be resized correctly and the cell will look how I expected it to initially.
I have also attempted calculating the labels frame with the same method I'm calculating the row height with, and I get the same behavior - it doesn't draw correctly until it scrolls off of the screen and back on again.
I have found two ways to work around this, and neither are acceptable solutions.
First, if in viewDidAppear: I call reloadData on my tableview, the cells and labels draw themselves correctly the first time. This won't work for my situation because I will be adding and removing cells to this table, and I don't want to call reloadData every time a cell is added.
The second workaround seems very strange to me - if I leave the font settings at the default System Font 17 on the UILabel, the cells draw themselves correctly. As soon as I change the font size, it reverts to its behavior of not drawing a label correctly until it leaves the screen and comes back, or gets reloadData called on the tableView.
I'd appreciate any help with this one.
I ended up resolving this by alloc/init'ing the label in cellForRowAtIndexPath. I'm not entirely sure why this is a solution - but it appears the problem I was experiencing has to do with how storyboard (or when, perhaps?) creates the objects within the cell. If I alloc/init the label in the cell in cellForRowAtIndexPath, everything loads and sizes correctly.
So... my current fix is to check if the cell has my custom label in it. If it doesn't, I alloc/init the label and put it in the cell. If it does have one, as in its a cell that's been dequeued, then I just set the text in the label that is already there.
Not sure if its the best solution, but its working for now.
I ended up resolving this by unchecking the AutoSizing checkbox in IB. It is unclear why auto-layout was causing this problem.
I ran over the same problem and I end up solving it by calling [cell layoutIfNeeded] before return the cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ExpandCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
SomeObject *object = self.tableObjects[index.row];
cell.myLabel.text = [object cellText];
[cell layoutIfNeeded];
return cell; }
In the following code, if we do [cell addSubview: someLabel] vs [cell.contentView addSubview: someLabel], they seem to work the same. Is there any difference doing one or the other? (the custom cell in the real code is adding UIImageView and UILabel) (UIView, on the other hand, doesn't have contentView, so we don't need to add subview to its contentView. UITableViewCell is a subclass of UIView by the way)
-(UITableViewCell *) tableView:(UITableView *) tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
if ([tableView isEqual:self.songsTableView]){
static NSString *TableViewCellIdentifier = #"MyCells";
cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:TableViewCellIdentifier];
}
// ... some code to create a UILabel (not shown here)
[cell addSubview: someLabel]; // vs using [cell.contentView addSubView: ...]
I believe If I am not wrong, the contentView is a subview of UITableViewCell.
If you look at this page here, you can see there are actually 3 subviews in a UITableViewCell
I think by default, the Editing Control is hidden until you enter edit mode for a table in which case, the Editing Control appears (the minus button left of each row) and your contentView gets resized and pushed to the right. This is probably what gives the "proper animation" effect mentioned by the other answer.
To test the difference, try adding a subview such as UILabel with text, to the cell rather than the cell.contentView. When you add it to cell rather than cell.contentView and you enter edit mode for your table, I believe your UILabel will not resize, you will see the edit button ontop/below the minus sign button.
Placing your views in the contentView affects proper animation in and out of edit mode. Place all of your subviews in contentView when you're not subclassing, which should be all of the time unless you know what you're doing.
So, the correct number of rows shows up. On pressing any row, the correct action takes place. However, the cells themselves are nowhere to be seen.
I added a NSTimer in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
for each cell just to trace it out beyond the function - they all say that their superview is equal to the tableview in question (and is not nil, so i'm not checking nil == nil or something).
They all contain labels with the correct text.
The separator lines are being drawn.... If I change the TableView background, the whole visible area's background shows as that color.
I'm checking that each cell is neither hidden nor set to an alpha of 0.
Is there anything else I could be missing?
Are you loading from your cells from a nib file or creating programmatically?
Are you overlaying another object over your cell in the cell subview? Perhaps a subview is covering it; I can't tell, since you have not posted any code yet. Given the information you have provided, it is difficult to determine why you cannot see the cells backgroundView.
Try changing the color with
UIView *tmpView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
tmpView.backgroundColor = [UIColor blackColor];
myCell.backgroundView = tmpView;
It sounds like you have set the backgroundView of your cell to [UIColor clearColor].