UITableView cell width on iOS 8 stuck at 320pt - ios

I am currently trying to create a simple UITableView with custom cells without using storyboard.
I'm getting an issue on the iPhone 6 simulator where the table view has a width of 375 (as it should), but the cells inside are getting a width of 320.
The number 320 is nowhere to be found in the project as I am not hard coding it. When I am setting the background colour of the cell, it extends the full width of 375, but I need to align an image to the right, which only aligns 320 across as shown in the photo below.
I'm not sure if it's because I'm missing constraints or if there's a bug. Any help is appreciated, thanks!
Code to set up table:
- (TBMessageViewCell *)getMessageCellforTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"MessageCell";
TBMessageViewCell *cell = (TBMessageViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[TBMessageViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell createSubviews];
}
// Set the new message and refresh
[cell setMessage:self.viewModel.messages[indexPath.row]];
[cell populateSubviews];
cell.backgroundColor = [UIColor blueColor];
NSLog(#"cell Width: %f", cell.contentView.frame.size.width);
return cell;
}
Complete TBMessageViewCell:
#implementation TBMessageViewCell
const CGFloat MARGIN = 10.0f;
const CGFloat AVATAR_SIZE = 40.0f;
-(id)initWithStyle:(UITableViewCellStyle *)style reuseIdentifier:(NSString *)reuseIdentifier
{
if(self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]){
}
// Sets background and selected background color
self.backgroundColor = [UIColor clearColor];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor clearColor];
self.selectedBackgroundView = selectionColor;
return self;
}
- (void)populateSubviews
{
// Set the message body
[self.messageBodyLabel setText:self.message.body];
[self.messageBodyLabel setTextAlignment:NSTextAlignmentRight];
CGRect bodyFrame = CGRectMake(MARGIN, MARGIN, self.frame.size.width - (AVATAR_SIZE + (MARGIN * 3)), self.frame.size.height);
// Calculates the expected frame size based on the font and dimensions of the label
// FLT_MAX simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(bodyFrame.size.width, FLT_MAX);
CGRect textRect = [self.message.body boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:self.messageBodyLabel.font}
context:nil];
bodyFrame.size.height = textRect.size.height;
// Setup the new avatar frame (Right aligned)
CGRect avatarFrame = CGRectMake(bodyFrame.size.width + (MARGIN * 2), MARGIN, AVATAR_SIZE, AVATAR_SIZE);
// Align to the LEFT side for current user's messages
if ([[TBConfig userID] isEqualToString:self.message.user.userID]) {
// Set avatar to left if it's me
avatarFrame.origin.x = MARGIN;
bodyFrame.origin.x = AVATAR_SIZE + (MARGIN * 2);
[self.messageBodyLabel setTextAlignment:NSTextAlignmentLeft];
}
self.avatar.frame = avatarFrame;
self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2;
self.messageBodyLabel.frame = bodyFrame;
// Set the new cell height on the main Cell
CGFloat cellHeight = MAX(bodyFrame.size.height, self.frame.size.height) + MARGIN;
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, cellHeight);
// Set the new Profile avatar
if (![self.avatar.profileID isEqualToString:self.message.user.facebookID]) {
[self.avatar setProfileID:nil];
[self.avatar setProfileID:self.message.user.facebookID];
}
}
- (void)createSubviews
{
self.messageBodyLabel = [[UILabel alloc] init];
self.messageBodyLabel.textColor = [UIColor whiteColor];
self.messageBodyLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.messageBodyLabel.numberOfLines = 0;
[self addSubview:self.messageBodyLabel];
// Creates the avatar
self.avatar = [[FBProfilePictureView alloc] init];
[self.avatar setPictureCropping:FBProfilePictureCroppingSquare];
[self addSubview:self.avatar];
}

You're printing the size of the cell before it has been added to the display — before it has been sized. It doesn't yet know the size of tableview it will be added to.
The cells will be given an appropriate frame when added to the display.
EDIT: oh, and you probably don't want that cellIdentifier to be static. You probably wanted *const.

Don't know if you have found the answer. I faced the same problem when I was trying to subclass UITableViewCell and add custom subviews programmatically without using xib.
Finally the solution worked for me is to use [[UIScreen mainScreen] applicationFrame] instead of self.frame when calculating subviews' frames.

The proper way to solve this is to perform your layout in the layoutSubviews method.
In your case, simply call "populateSubviews" within "layoutSubviews" method, like this:
- (void)layoutSubviews {
[super layoutSubviews];
[self populateSubviews];
}
... but before doing this I would recommend that you do content population in a separate method (ie, calls to label.text = ...), and place all layout-affecting calls (ie, label.frame = ...) below [super layoutSubviews] in the method above.
That would result in something like:
- (void)layoutSubviews {
[super layoutSubviews];
CGRect bodyFrame = CGRectMake(MARGIN, MARGIN, self.frame.size.width - (AVATAR_SIZE + (MARGIN * 3)), self.frame.size.height);
// Calculates the expected frame size based on the font and dimensions of the label
// FLT_MAX simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(bodyFrame.size.width, FLT_MAX);
CGRect textRect = [self.message.body boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:self.messageBodyLabel.font}
context:nil];
bodyFrame.size.height = textRect.size.height;
// .. the rest of your layout code here ..
}
- (void)populateSubviews {
[self.messageBodyLabel setText:self.message.body];
// .. the rest of your code here ..
}

After you set your avatar frame in:
self.avatar.frame = avatarFrame;
self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2;
self.messageBodyLabel.frame = bodyFrame;
write
self.avatar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
It should hook your avatar image to the right margin and leave the left margin as flexible.

Select your table view cell's connection inspector and check if you haven't connected editingAccessoryView by mistake

While this answer may not be as straightforward as you'd expect UIKit to deliver, due to a bug in UITableView - when doing things programmatically - you gotta get your hands dirty. Xib lovers - be warned - this answer isn't for you. It's probably just working.
In later IOS versions, let's hope this problem get resolved. The problem is uitableview is hardcoding the dimensions of the cell to 320. In one project I had - I was forcing the frame size to to fix this. N.B. this has problems with splitview controller on iPad.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"cell frame width:%f",cell.frame.size.width); // you should see <- 320! WTH
// you can crudely correct this here
cell.frame = CGRectMake(0,0,[[UIScreen mainScreen] applicationFrame].size.width,CELL_HEIGHT);
}
Another option - that's working better for me is a local width variable to reference. I know this code is not ideal - but it works consistently.
#interface AbtractCustomCell : UITableViewCell {
float width;
}
#end
#implementation AbtractCustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//optimise speed
// [self setOpaque:YES];
if ([SDiPhoneVersion deviceSize] == iPhone47inch) {
width = 375;
}
else if ([SDiPhoneVersion deviceSize] == iPhone47inch) {
width = 414;
}
else {
width = 320; // hardcode iphone 4/5 /ipad2
}
}
return self;
}
#end
then you have the option to make TBMessageViewCell a subclass of this AbstractCustomCell which will have this variable there for you. Instead of using self.contentView.bounds.size.width / self.bounds.size.width just use width.

I'm programmatically layout without Storyboard and facing same issue, and I need to return the cell upon cellForRowAt indexPath which in turn it still didnt manage to get the container size yet.
And I manage to solve it by move the layout codes into willDisplay cell delegate.

Related

Calculate Cell height on basis of label text + image

I have created a custom cell that have IMAGE view, and two label's the data of labels's are populated from a plist file, the data is populated properly but on front end the cell didn't show the data properly, the label cut's the data. I am using Uilabel view's.
Please have a view to my code, i have search over internet and followed some tutorial's as well but nothing work's.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Customviewcell *cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
UIImage * image = [UIImage imageNamed:justThumbs[indexPath.row]];
cell.CustomTitle.text=justTitles[indexPath.row];
cell.CustomTitle.numberOfLines =0;
[cell.CustomTitle sizeToFit];
cell.CustomDes.text=justDesc[indexPath.row];
cell.CustomDes.numberOfLines=0;
[cell.CustomDes sizeToFit];
[cell.CustomTitle layoutIfNeeded];
[cell.CustomDes layoutIfNeeded];
[cell layoutIfNeeded];
cell.Customimage.image=image;
return cell;
}
Code for calculating the height as per stackoverflow different question's answer's.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Calculate Height Based on a cell
if (!self.customcell) {
self.customcell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
}
// Configure Cell
UIImage * image = [UIImage imageNamed:justThumbs[indexPath.row]];
self.customcell.CustomTitle.text=justTitles[indexPath.row];
self.customcell.CustomTitle.numberOfLines=0;
[self.customcell.CustomTitle sizeToFit];
self.customcell.CustomDes.text=justDesc[indexPath.row];
self.customcell.CustomDes.numberOfLines=0;
[self.customcell.CustomDes sizeToFit];
self.customcell.Customimage.image=image;
//Layout Cell
//Get Hieght for the cell
if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone)
{
if ([[UIScreen mainScreen] bounds].size.height == 568)
{
CGRect frame = [NSString setAttributeWithString:self.customcell.CustomTitle.text withLineSpacing:0.2 withSize:CGSizeMake(270, 999999999) withFont:self.customcell.CustomTitle.font withLabel:self.customcell.CustomTitle setLabelTextColor:self.customcell.CustomTitle.textColor setTextAlignment:self.customcell.CustomTitle.textAlignment];
self.customcell.CustomTitle.height.constant = frame.size.height;
frame = [NSString setAttributeWithString:self.customcell.CustomDes.text withLineSpacing:0.3 withSize:CGSizeMake(150, 999999999) withFont:self.customcell.CustomDes.font withLabel:self.customcell.CustomDes setLabelTextColor:self.customcell.CustomDes.textColor setTextAlignment:self.customcell.CustomDes.textAlignment];
self.customcell.CustomDes.height.constant = frame.size.height;
}
else{
CGRect frame = [NSString setAttributeWithString:self.customcell.CustomTitle.text withLineSpacing:1 withSize:CGSizeMake(337, 999999999) withFont:self.customcell.CustomTitle.font withLabel:self.customcell.CustomTitle setLabelTextColor:self.customcell.CustomTitle.textColor setTextAlignment:self.customcell.CustomTitle.textAlignment];
self.customcell.CustomTitle.height.constant = frame.size.height;
frame = [NSString setAttributeWithString:self.customcell.CustomDes.text withLineSpacing:1 withSize:CGSizeMake(227, 999999999) withFont:self.customcell.CustomDes.font withLabel:self.customcell.CustomDes setLabelTextColor:self.customcell.CustomDes.textColor setTextAlignment:self.customcell.CustomDes.textAlignment];
self.customcell.CustomDes.height.constant = frame.size.height;
}
}
[self.customcell layoutIfNeeded];
// CGFloat height = self.customcell.CustomTitle.height.constant+self.customcell.CustomDes.height.constant+189;
CGFloat height = [self.customcell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
//Add padding of 1
return height;
}
Used Github opensource library to solve the issue but didn't worked.
https://github.com/punchagency/line-height-tool
Issue still remain's, text of label's cut off, content hanging is at Required and Content is at 1000 horizontal + vertical..
Please help..
Thanks allot.
You can get the height of a string in certain bounds with the NSString method boundingRectWithSize, like
NSString* text = #"Test text";
CGRect textRect = [text boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName : [UIFont systemFontOfSize:12]}
context:nil];
CGFloat textHeight = ceilf(textRect.size.height);
Use your own font and font size, and you can also add other attributes to the attributes dictionary if necessary.
Use following method to calculate your UILabel height:
add also use this method in your class.
- (CGFloat)getLabelHeight:(UILabel*)label{
CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
CGSize size;
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [label.text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:label.font}
context:context].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
return size.height;}
Update your heightForRowAtIndexPath Method as per your requirement:
calculate all UI Height and return.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
Customviewcell *cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
CGFloat totalHeight = 0;
cell.CustomTitle.text=justTitles[indexPath.row];
//get label Height
totalHeight += [Helper getLabelHeight:cell.CustomTitle];
cell.Customimage.image = [UIImage imageNamed:justThumbs[indexPath.row]];
CGFloat imageHeight = cell.Customimage.frame.size.height; //or Add image height here
totalHeight += imageHeight;
return totalHeight;}
In iOS8+ you can use self sizing cells:
http://www.appcoda.com/self-sizing-cells/
Auto Resizing of Cell is available in Ios 8.0, The issue my deployment target was ios 7.0, which is causing the layout issues.
Please refer to these articles:
http://www.appcoda.com/self-sizing-cells/
The Code is in swift but need to do same thing's in objective c as well.
This will also help's you.
http://useyourloaf.com/blog/self-sizing-table-view-cells.html

UIScrollView paging with animation

I have achieved the following using UIScrollView and enabled paging.
I want the centre element of the scrollview to show little bigger than other elements. Need to increase/decrease the font of the text label as the scroll view is scrolling depending on its location.
I tried using transform but hard luck.
Code for adding the label's:
array = [[NSMutableArray alloc] init];
for(int i=0;i<10;i++){
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(x, 0, 150, 50)];
label.text = [NSString stringWithFormat:#"ID - %d",i];
label.textAlignment = UITextAlignmentCenter;
x +=150;
[self.scrollView addSubview:label];
[array addObject:label];
}
[self.scrollView setContentSize:CGSizeMake(x, 50)];
Animation which I performed in ScollViewDidScroll
float position = label.center.x - scrollView.contentOffset.x;
float offset = 2.0 - (fabs(scrollView.center.x - position) * 1.0) / scrollView.center.x;
label.transform = CGAffineTransformIdentity;
label.transform = CGAffineTransformScale(label.transform,offset, offset);
CODE: What I have achieved till now:
https://www.dropbox.com/s/h2q4qvg3n4fi34f/ScrollViewPagingPeeking.zip?dl=0
Don't use scrollview, used UICollectionView and Make collectionView cell bigger as screen size.
And Enable it's paging property than used it's delegate methods.
It's more preferable and efficient way of paging.
It will work using a collection view. Return layout attributes where the transform scale is calculated according to the position. Subclass the UICollectionViewLayout you are using (probably UICollectionViewFlowLayout). To get the resizing based on position to work you should override a few of its methods thusly:
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *array = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attributes in array)
{
[self updateLayoutAttributesForItemAtIndexPath:layoutAttributes];
}
return array;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes *layoutAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
[self updateLayoutAttributesForItemAtIndexPath:layoutAttributes];
}
- (UICollectionViewLayoutAttributes *)updateLayoutAttributesScaleForPosition:(UICollectionViewLayoutAttributes *)layoutAttributes
{
// NOTE: Your code assigning an updated transform scale based on the cell position here
return layoutAttributes;
}
Probably the main thing you were missing was the override to the shouldInvalidateLayoutForBoundsChange: method

Laggy when switching tabBarController to a tableView with many cells

My app is based on a tabBarController and has 2 tabs.
I load data for the 2nd tab in the background while the app launches at tab 1, so users don't need to wait when they click tab 2.
My problem is: it's laggy to switch to tab 2 if I load the data in advance and there is much data to show in cells of the tableView belonging to tab 2. If there are not many cells to show, then it's not laggy at all.
I guess it's because generating cells is time-consuming, so the view is blocked when there are too many cells. How do I optimize this?
Important! This code has not been tested in the XCode, but contains some parts from real projects.
The CellView class could be created either as a Nib or even manually using calculateCellHeight method from ServicesHelper.m. In both cases the layoutSubviews method must be implemented where the resize detailTextLabel UILabel code to be placed. The CellView labels Font and Color must be the same as used in calculateCellHeight method.
ServicesHelper.m
#define FontRegular(fontSize) [UIFont fontWithName:#"HelveticaNeue" size:fontSize]
// the height of fixed part of the cell, fixed height UILabel + some padding
#define kFixedPartCellHeight 20
#define kLeftPaddingWidth 20
#define kLandscapeHeightKey #"landscapeKey"
#define kPortraitHeight #"portraitKey"
+ (NSDictionary *) calculateCellHeight: (NSString *) text {
// dynamic height label
UILabel *detailTextLabel = [UILabel new];
UIFont *mainFont = FontRegular(14.0);
// specifying font and colour to be used inside cell is important to get precise frame rect
[detailTextLabel setFont: mainFont];
[detailTextLabel setTextColor:[UIColor blackColor]];
detailTextLabel.lineBreakMode = NSLineBreakByWordWrapping;
detailTextLabel.numberOfLines = 0;
[textLabel setBackgroundColor: [UIColor clearColor]];
[detailTextLabel setBackgroundColor: [UIColor clearColor]];
// get the width of the cell for both orientations
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat landscapeWidth = MAX (screenRect.size.width, screenRect.size.height);
CGFloat portraitWidth = MIN (screenRect.size.width, screenRect.size.height);
// kLeftPaddingWidth - is just a white space left and right to the UILabel inside cell
// we set the UILabel width with maximum possible height, then set text and shrink it using sizeToFit to get the exact size
detailTextLabel.frame = CGRectMake (0, 0 , landscapeWidth - kLeftPaddingWidth * 2, CGFLOAT_MAX);
textLabel.frame = detailTextLabel.frame;
detailTextLabel.text = text;
[detailTextLabel sizeToFit];
CGFloat landscapeHeight = detailTextLabel.frame.size.height + kFixedPartCellHeight;
detailTextLabel.frame = CGRectMake (0, 0 , portraitWidth - kLeftPaddingWidth * 2, CGFLOAT_MAX);
textLabel.frame = detailTextLabel.frame;
detailTextLabel.text = text;
[detailTextLabel sizeToFit];
CGFloat portraitHeight = detailTextLabel.frame.size.height + kFixedPartCellHeight;
return #{kLandscapeHeightKey: landscapeHeight, kPortraitHeightKey: portraitHeight};
}
TableView.h
#property (nonatomic, strong) NSMutableArray *arrayOfTexts;
#property (nonatomic, strong) NSMutableDictionary *dictOfHeights;
TableView.m
- (void) precalculateHeight {
if (nil == self.dictOfHeights) self.dictOfHeights = [NSMutableDictionary new];
CGRect screenRect = [[UIScreen mainScreen] bounds];
// height of two screens
CGFloat maxHeight = MAX (screenRect.size.width, screenRect.size.height) * 2;
CGFloat totalHeight = 0;
CGFloat portraitHeight;
CGFloat landscapeHeight;
NSDictionary *dictHeights;
for (int i = 0; i < self.arrayOfTexts.count; i++ ) {
dictHeights = [ServicesHelper calculateCellHeight: arrayOfTexts[i]];
portraitHeight = [dictHeights[kPortraitHeightKey] floatValue];
[self.dictOfHeights setValue: dictHeights forKey:#(i)];
totalHeight += portraitHeight;
if (totalHeight > maxHeight) break;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.dictOfHeights && self.dictOfHeights[#(indexPath.row)]) {
return UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation) ?
[self.dictOfHeights[#(indexPath.row)][kPortraitHeightKey] floatValue] :
[self.dictOfHeights[#(indexPath.row)][kLandscapeHeightKey] floatValue];
} else {
// you decide, call calculateCellHeight for particular row, right from here, or also calculate rows height for the coming set of cells
// #todo:
}
return CGFLOAT_MIN;
}

UILabel have a weird grey top line/border in iOS7, how can I remove it?

I have a basic UILabel that I use in a UITableViewCell. I'm experiencing some strange behaviour, on some cells (not all) the UILabel gets a grey top border, see picture below. And I'm not sure how to fix it.
I create my UILabel like this:
if (self.postText == nil) {
CGRect postTextRect = CGRectMake(self.profileImage.frame.origin.x + self.profileImage.frame.size.width + 5, self.username.frame.origin.y + self.username.frame.size.height, frame.size.width - self.profileImage.frame.size.width - self.profileImage.frame.origin.y -10, self.frame.size.height - self.username.frame.size.height - self.username.frame.origin.y + 40);
self.postText = [[UILabel alloc] initWithFrame:postTextRect];
self.postText.backgroundColor = [UIColor whiteColor];
self.postText.textColor = [UIColor darkGrayColor];
self.postText.userInteractionEnabled = NO;
self.postText.numberOfLines = 0;
[self.containerView addSubview:self.postText];
}
Any ideas on how to fix this?
Update
My cellForRowAtIndexPath looks like this:
- (id)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[...]
static NSString *postCellIdentifier = #"PostCell";
PostCell *cell = [tableView dequeueReusableCellWithIdentifier:postCellIdentifier];
if (cell == nil) {
cell = [[PostCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:postCellIdentifier];
}
[self configureCell:cell atIndexPath:indexPath forPost:cellPost];
return cell;
}
And the relevant par of configureCell like this:
- (void)configureCell:(PostCell *)cell atIndexPath:(NSIndexPath *)indexPath forPost:(Post *)post
{
[...]
cell.username.text = cellUser.username;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
CGSize maximumLabelSize = CGSizeMake(cell.postText.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [cell.postText.text sizeWithFont:cell.postText.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect newFrame = cell.postText.frame;
newFrame.size.height = expectedLabelSize.height;
cell.postText.frame = newFrame;
CGRect containerRect = CGRectMake(5, 5, cell.containerView.frame.size.width, cell.postText.frame.size.height + cell.username.frame.origin.y + cell.username.frame.size.height + 10);
if (containerRect.size.height < 65) {
containerRect.size.height = 65;
}
cell.containerView.frame = containerRect;
[...]
}
I had the same problem and solved it by rounding up the height:
newFrame.size.height = ceilf(expectedLabelSize.height);
Got the same issue
Solved by assigning border color and width to UILabel
nameLabel.layer.borderColor = [[UIColor whiteColor]CGColor];
nameLabel.layer.borderWidth = 2.0f;
It must be a iOS's bug. The bug is triggered by the float height value of the label. So, the easy and no side-effect way to solve it is converting the float height value to int value:
(int)(label.frame.size.height)
Decided to use a UITextView instead.
The problem seems to occur when changing the UILabel's frame.
Chaning this code:
CGSize maximumLabelSize = CGSizeMake(cell.postText.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [cell.postText.text sizeWithFont:cell.postText.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect newFrame = cell.postText.frame;
newFrame.size.height = expectedLabelSize.height;
cell.postText.frame = newFrame;
to...
[cell.postText sizeToFit];
Did remove the border. But the content wasn't displayed just as I wanted it, that's why I changed to UITextView
The weird grey outlines is due to the background size and label size is not exact the same.
It can be solved perfectly by:
[myLabel sizeToFit]
The real reason is your frame height or width is not integer or change your app view` background color to clear color.
把frame的width 或者height修改为整数,或者设置背景色为clear color 即可.
try this:
cell.postText.layer.borderColor = self.Detail.backgroundColor.CGColor;
cell.postText.layer.borderWidth = 1;
It's seem that the problem appears when you change the frame property of the label, setting width or height with float value.
This solution works for me, setting the backgroundColor of the label to Clear.
Objective-C:
[label setBackgroundColor:[UIColor clearColor]];
swift:
label.setBackgroundColor = UIColor.clearColor()
I had the same issue. just doing labelView.layer.opaque = false; fixed mine. hope this will be useful to someone.
I found this problem in a .xib that was partially implemented with Auto Layout and partially implemented with Translates Mask Into Constraints. Once I converted it to full Auto Layout, the problem went away even though the sizes still had some half-points.

Part of cell bounds stays on screen while try to edit the width of the UITableViewCell

I have a UITableView with grouped style and UITableViewCell, which I need to make a little bit wider. So, I subclassing the UITableViewCell and implement there a method:
- (void) layoutSubviews
{
[super layoutSubviews];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && !IS_OS_7_OR_LATER) {
CGRect frame = self.frame;
frame.origin.x -= 10;
frame.size.width += 20;
self.frame = frame;
}
}
Now there is a problem - my cell looks like this:
and with colour layers on:
In the top of the cell there is a part of the bounds of the previous cell before resizing.. This you can see much clearly on the second screen. Can you help me how to remove this border?
UIView *backgroundView = [[UIView alloc] initWithFrame:cell.bounds];
backgroundView.backgroundColor = [UIColor colorWithRed:240 green:240 blue:240 alpha:1];
cell.backgroundView = backgroundView;
have a try.

Resources