UITableview Cell Height is not calculated properly and cells overlap - ios

I need to create and populate custom cells. These cells height are huge about 300-400.
So I have a populateCellView function , I call that function on heightForRowAtIndexPath to calculate height and in cellForRowAtIndexPath to add that view to cell content view, but somehow sometimes cells overlap.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self populateCellView:indexPath.row].frame.size.height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *populateCell= nil;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
populateCell=[[UIView alloc] initWithFrame:CGRectZero];
[[populateCell layer] setBorderWidth:2.0f];
populateCell= [self populateCellView:indexPath.row];
[[cell contentView] addSubview:populateCell];
}
if (!populateCell){
populateCell = (UIView*)[cell viewWithTag:1];
populateCell= [self populateCellView:indexPath.row];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
populate view function:
-(UIView *)populateCellView:(int)forCase
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width,500)];
[view setBackgroundColor:[UIColor colorWithRed:40/255.0 green:150/255.0 blue:213/255.0 alpha:1.0]];
view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
if ([view subviews]){
for (UIView *subview in [view subviews]) {
[subview removeFromSuperview];
}
}
UILabel *caseNumberLabel;
UILabel *caseNameLabel;
UILabel *caseSummaryLabel;
UILabel *caseAncLabel;
UILabel *caseNumberText;
UILabel *caseNameText;
UILabel *caseSummaryText;
UILabel *caseAncText;
//static label for case number
caseNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,10,250, 50)];
caseNumberLabel.textColor = [UIColor whiteColor];
caseNumberLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseNumberLabel.text =#"Case Number:";
caseNumberLabel.backgroundColor = [UIColor clearColor];
caseNumberLabel.numberOfLines=0;
caseNumberLabel.adjustsFontSizeToFitWidth = NO;
caseNumberLabel.tag=forCase;
caseNumberLabel.frame=[self calculateLabelFrame:caseNumberLabel];
//case number from plist
caseNumberText = [[UILabel alloc] initWithFrame:CGRectMake(caseNumberLabel.frame.size.width+50,caseNumberLabel.frame.origin.y,self.view.frame.size.width-caseNumberLabel.frame.size.width-50, 50)];
caseNumberText.textColor = [UIColor whiteColor];
caseNumberText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseNumberText.text =[[self agenda] getCaseNumber:forCase];
caseNumberText.backgroundColor = [UIColor clearColor];
caseNumberText.numberOfLines=0;
caseNumberText.adjustsFontSizeToFitWidth = NO;
caseNumberText.tag=forCase;
//[caseNumberLabel sizeToFit];
caseNumberText.frame=[self calculateLabelFrame:caseNumberText];
//static label for case name
caseNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseNumberText.frame.origin.y + caseNumberText.bounds.size.height+5,250, 50)];
caseNameLabel.textColor =[UIColor whiteColor];
caseNameLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseNameLabel.text =#"Case Name:";
caseNameLabel.backgroundColor = [UIColor clearColor];
caseNameLabel.numberOfLines=0;
caseNameLabel.adjustsFontSizeToFitWidth = NO;
caseNameLabel.tag=forCase;
//[caseNumberLabel sizeToFit];
caseNameLabel.frame=[self calculateLabelFrame:caseNameLabel];
//case name from plist
caseNameText = [[UILabel alloc] initWithFrame:CGRectMake(caseNameLabel.frame.size.width+50,caseNameLabel.frame.origin.y,self.view.frame.size.width-caseNameLabel.frame.size.width-50, 50)];
caseNameText.textColor = [UIColor whiteColor];
caseNameText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseNameText.text =[[self agenda] getCaseName:forCase];
caseNameText.backgroundColor = [UIColor clearColor];
caseNameText.numberOfLines=0;
//caseNameText.adjustsFontSizeToFitWidth = NO;
caseNameText.tag=forCase;
[caseNameText sizeToFit];
//caseNameText.lineBreakMode = NSLineBreakByWordWrapping;
caseNameText.frame=[self calCellLabelFrame:caseNameText previousLabel:caseNameLabel];
//static label for case summary
caseSummaryLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseNameText.frame.origin.y + caseNameText.bounds.size.height+20,250, 50)];
caseSummaryLabel.textColor = [UIColor whiteColor];
caseSummaryLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseSummaryLabel.text =#"Case Summary:";
caseSummaryLabel.backgroundColor = [UIColor clearColor];
caseSummaryLabel.numberOfLines=0;
caseSummaryLabel.adjustsFontSizeToFitWidth = NO;
caseSummaryLabel.tag=forCase;
//[caseSummaryLabel sizeToFit];
caseSummaryLabel.frame=[self calculateLabelFrame:caseSummaryLabel];
//case name from plist
caseSummaryText = [[UILabel alloc] initWithFrame:CGRectMake(caseSummaryLabel.frame.size.width+50,caseSummaryLabel.frame.origin.y,self.view.frame.size.width-caseSummaryLabel.frame.size.width-100, 50)];
caseSummaryText.textColor = [UIColor whiteColor];
caseSummaryText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseSummaryText.text =[[self agenda] getCaseSummary:forCase];
caseSummaryText.backgroundColor = [UIColor clearColor];
caseSummaryText.numberOfLines=0;
//caseSummaryText.adjustsFontSizeToFitWidth = NO;
caseSummaryText.tag=forCase;
[caseSummaryText sizeToFit];
//caseSummaryText.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
caseSummaryText.frame=[self calCellLabelFrame:caseSummaryText previousLabel:caseSummaryLabel];
//static label for anc
caseAncLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseSummaryText.frame.origin.y + caseSummaryText.bounds.size.height+15,250, 50)];
caseAncLabel.textColor = [UIColor whiteColor];
caseAncLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseAncLabel.text =#"ANC:";
caseAncLabel.backgroundColor = [UIColor clearColor];
caseAncLabel.numberOfLines=0;
caseAncLabel.adjustsFontSizeToFitWidth = NO;
caseAncLabel.tag=forCase;
//[ccaseAncLabel sizeToFit];
caseAncLabel.frame=[self calculateLabelFrame:caseAncLabel];
//case name from plist
caseAncText = [[UILabel alloc] initWithFrame:CGRectMake(caseAncLabel.frame.size.width+50,caseAncLabel.frame.origin.y,self.view.frame.size.width-caseAncLabel.frame.size.width-50, 50)];
caseAncText.textColor = [UIColor whiteColor];
caseAncText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseAncText.text =[[self agenda] getCaseAnc:forCase];
caseAncText.backgroundColor = [UIColor clearColor];
caseAncText.numberOfLines=0;
//caseAncText.adjustsFontSizeToFitWidth = NO;
caseAncText.tag=forCase;
[caseAncText sizeToFit];
//caseSummaryText.lineBreakMode = NSLineBreakByWordWrapping;
caseAncText.frame=[self calCellLabelFrame:caseAncText previousLabel:caseAncLabel];
//add button
UIButton *acceptButton=[UIButton buttonWithType:UIButtonTypeCustom];
[acceptButton setTag:forCase];
acceptButton.titleLabel.tag=1;
[acceptButton setFrame:CGRectMake(caseAncLabel.frame.size.width+50,caseAncText.frame.origin.y + caseAncText.bounds.size.height+20,181,39)];
NSString *radioButtonImage=#"view_attachment.png";
UIImage *acceptbuttonImage = [UIImage imageNamed:radioButtonImage];
[acceptButton setBackgroundImage:acceptbuttonImage forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(showAttachements:) forControlEvents:UIControlEventTouchUpInside];
//whie line
UIView *anotherline = [[UIView alloc] initWithFrame:CGRectMake(0, acceptButton.frame.origin.y + acceptButton.bounds.size.height+15, self.view.frame.size.width, 1)];
anotherline.backgroundColor=[UIColor whiteColor];
anotherline.tag=forCase;
[view addSubview:acceptButton];
[view addSubview: caseNumberLabel];
[view addSubview:caseNumberText];
[view addSubview:caseNameLabel];
[view addSubview:caseNameText];
[view addSubview:caseSummaryLabel];
[view addSubview:caseSummaryText];
[view addSubview:caseAncText];
[view addSubview:caseAncLabel];
[view addSubview:anotherline];
view.frame = CGRectMake(0,0, self.view.frame.size.width,anotherline.frame.origin.y + anotherline.bounds.size.height+5);
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
view.backgroundColor = [UIColor colorWithRed: redLevel
green: greenLevel
blue: blueLevel
alpha: 1.0];
return view;
}
I call reload data like this
dispatch_async(dispatch_get_main_queue(), ^{
[_agenda loadFromPlist];
[[self tableView] reloadData];
});
Any idea why cells overlaps?

Its your UITableview cellforIndexPath causing overlap
try this
if (!populateCell){
populateCell = (UIView*)[cell viewWithTag:1];
populateCell= [self populateCellView:indexPath.row];
if ([[cell contentView] subviews]){
for (UIView *subview in [[cell contentView] subviews]) {
[subview removeFromSuperview];
}
}
[[cell contentView] addSubview:populateCell];
}
cell.backgroundColor=[UIColor clearColor];

At the end of the UITableViewDataSource method, tableView:cellForRowAtIndexPath:, you have to call [[cell contentView] addSubView:populateCell]. If the table dequeued a cell successfully, you have to retrieve the appropriate populateCell and add it to the contentView.

If you use storyboards, and set a different height for the cells, and the rows in the tableview, the height will usually overlap. The other answers are also highly valid, but usually when I've encountered this problem, the bug lies in a different value on row height and cell height in the tableview object in your storyboard...

Related

IOS, How to set Auto Layout in your UITableViewCell that contains different Subviews

I have a layout issue, i have a UIView that contains an UIImageView and three other UILabels. The part that needs to set the layout dynamically is the main UIView thats added to the cell and a UILabel that will contain text of any length lets say for this example.
What i have done i created a custom UITableViewCell and added the SubViews to the custom UITableViewCell, like here:
-(void)setupView:(PostInfo*)postInfo{
CGRect screenRect = [[UIScreen mainScreen] bounds];
viewPostMessage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, screenRect.size.width - 20, 100)];
viewPostMessage.backgroundColor = [UIColor colorWithRed:193.0f/255 green:193.0f/255 blue:193.0f/255 alpha:1.0f];
viewPostMessage.layer.borderColor = [UIColor blackColor].CGColor;
viewPostMessage.layer.borderWidth = 0.5f;
if(postInfo.userImage.length > 0){
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
UIImage *imageUser = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://www.hugt.co.uk/userimage/%d/userImage.jpg", postInfo.userId]]]];
userImage.image = imageUser;
[viewPostMessage addSubview:userImage];
}else{
UIView *viewImage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
viewImage.backgroundColor = [UIColor colorWithRed:132.0f/255 green:132.0f/255 blue:132.0f/255 alpha:1.0f];
[viewPostMessage addSubview:viewImage];
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
UIImage *imageUser = [UIImage imageNamed:#"defaultuser.jpg"];
userImage.image = imageUser;
[viewImage addSubview:userImage];
}
labelUserName = [[UILabel alloc] initWithFrame:CGRectMake(50, 8, 200, 16)];
labelUserName.textColor = [UIColor colorWithRed:56.0f/255 green:56.0f/255 blue:57.0f/255 alpha:1.0f];
labelUserName.text = [NSString stringWithFormat:#"%# %# posted...", postInfo.firstName,postInfo.lastName];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelUserName.font = [UIFont fontWithName:#"Helvetica" size:12];
labelUserName.userInteractionEnabled = YES;
[viewPostMessage addSubview:labelUserName];
labelCreated = [[UILabel alloc] initWithFrame:CGRectMake(50, 24, 200, 16)];
labelCreated.textColor = [UIColor colorWithRed:86.0f/255 green:152.0f/255 blue:179.0f/255 alpha:1.0f];
labelCreated.text = [NSDateFormatter localizedStringFromDate:postInfo.timeStampCreated dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"AM" withString:#""];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"PM" withString:#""];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelCreated.font = [UIFont fontWithName:#"Helvetica" size:12];
labelCreated.userInteractionEnabled = YES;
[viewPostMessage addSubview:labelCreated];
labelMessage = [[UILabel alloc] initWithFrame:CGRectMake(50, 43, 210, 50)];
labelMessage.textColor = [UIColor colorWithRed:141.0f/255 green:142.0f/255 blue:142.0f/255 alpha:1.0f];
labelMessage.text = postInfo.message;
labelMessage.numberOfLines = 3;
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelMessage.font = [UIFont fontWithName:#"Helvetica" size:12];
labelMessage.userInteractionEnabled = YES;
[labelMessage sizeToFit];
[viewPostMessage addSubview:labelMessage];
[self.contentView addSubview:viewPostMessage];
}
When i create this custom UITableViewCell i pass in an object that sets the text on the UILabels, like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cell";
if(tableViewThreads == tableView){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
ThreadInfo *threadInfo = (ThreadInfo*)[self.threadsArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:[self setupThreadItem:threadInfo]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
if(tableViewPosts == tableView){
PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
PostInfo *postInfo = (PostInfo*)[self.postsArray objectAtIndex:indexPath.row];
[cell setupView:postInfo];
//[cell addSubview:[self setupPostItem:postInfo]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
//[cell.contentView addSubview:[self setupThreadItem:threadInfo]];
}
return nil;
}
I have searched the web and also here to find out how to Auto Layout the Subviews in the cell but can't seem to understand what needs to go next. I read that you need a Prototype Cell so i created a custom UITableViewCell and thats how far I've got.
Any help would be appreciated, thanks.
So far i have got the cells to resize with Auto Layout but i have removed the UIView that sits inside the cell, so now i have three UILabels and an UIImageView which are the UIImageView (userImage), UILabel (labelUsername), UILabel (labelCreated) and UILabel (labelMessage). So the dimensions and coordinates are the same just that the UIView has been removed:
First i set up NSLayoutContsraints in my Custom Cell, code bellow:
Set numberOFLines = 0 and remove sizeToFit on the UILabel thats going to AutoLayout.
-(void)setupView:(PostInfo*)postInfo{
CGRect screenRect = [[UIScreen mainScreen] bounds];
viewPostMessage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, screenRect.size.width - 20, 100)];
viewPostMessage.backgroundColor = [UIColor colorWithRed:193.0f/255 green:193.0f/255 blue:193.0f/255 alpha:1.0f];
viewPostMessage.layer.borderColor = [UIColor blackColor].CGColor;
viewPostMessage.layer.borderWidth = 0.5f;
if(postInfo.userImage.length > 0){
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
UIImage *imageUser = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://www.hugt.co.uk/userimage/%d/userImage.jpg", postInfo.userId]]]];
userImage.image = imageUser;
[self.contentView addSubview:userImage];
}else{
UIView *viewImage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
viewImage.backgroundColor = [UIColor colorWithRed:132.0f/255 green:132.0f/255 blue:132.0f/255 alpha:1.0f];
[self.contentView addSubview:viewImage];
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
UIImage *imageUser = [UIImage imageNamed:#"defaultuser.jpg"];
userImage.image = imageUser;
[viewImage addSubview:userImage];
}
labelUserName = [[UILabel alloc] initWithFrame:CGRectMake(50, 8, 200, 16)];
labelUserName.textColor = [UIColor colorWithRed:56.0f/255 green:56.0f/255 blue:57.0f/255 alpha:1.0f];
labelUserName.text = [NSString stringWithFormat:#"%# %# posted...", postInfo.firstName,postInfo.lastName];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelUserName.font = [UIFont fontWithName:#"Helvetica" size:12];
labelUserName.userInteractionEnabled = YES;
[self.contentView addSubview:labelUserName];
labelCreated = [[UILabel alloc] initWithFrame:CGRectMake(50, 24, 200, 16)];
labelCreated.textColor = [UIColor colorWithRed:86.0f/255 green:152.0f/255 blue:179.0f/255 alpha:1.0f];
labelCreated.text = [NSDateFormatter localizedStringFromDate:postInfo.timeStampCreated dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"AM" withString:#""];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"PM" withString:#""];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelCreated.font = [UIFont fontWithName:#"Helvetica" size:12];
labelCreated.userInteractionEnabled = YES;
[self.contentView addSubview:labelCreated];
labelMessage = [[UILabel alloc] initWithFrame:CGRectMake(50, 43, 210, 50)];
labelMessage.textColor = [UIColor colorWithRed:141.0f/255 green:142.0f/255 blue:142.0f/255 alpha:1.0f];
labelMessage.text = postInfo.message;
labelMessage.numberOfLines = 0;
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelMessage.font = [UIFont fontWithName:#"Helvetica" size:12];
labelMessage.userInteractionEnabled = YES;
labelMessage.lineBreakMode = NSLineBreakByWordWrapping;
//[labelMessage sizeToFit];
[self.contentView addSubview:labelMessage];
labelMessage.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[bodyLabel]-19-|" options:0 metrics:nil views:#{ #"bodyLabel": labelMessage }]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-43-[bodyLabel]-6-|" options:0 metrics:nil views:#{ #"bodyLabel": labelMessage }]];
//[self.contentView addSubview:viewPostMessage];
}
Then in my ViewController that contains the UITableVIew, i modified this bit of code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"cell";
if(tableViewThreads == tableView){
return 122;
}
if(tableViewPosts == tableView){
PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
PostInfo *postInfo = (PostInfo*)[self.postsArray objectAtIndex:indexPath.row];
[cell setupView:postInfo];
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGFloat h = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return h + 1;
}
return 0;
}
The Cells do now resize and the UILabel resizes automatically now but my other problem is that the UITableView scroll is not smooth so ill have to fix that, and when i scroll in the UITableView the Cell data from the UILabel (labelMessage) seems to print it self in other cells, don't know why this is
BUT the Cells resize and the other issues ill ask another question on here.
Sorry forgot to add this bit of code that sits in the PostTableViewCell:
- (void)layoutSubviews
{
[super layoutSubviews];
// Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
// need to use to set the preferredMaxLayoutWidth below.
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
// Set the preferredMaxLayoutWidth of the mutli-line bodyLabel based on the evaluated width of the label's frame,
// as this will allow the text to wrap correctly, and as a result allow the label to take on the correct height.
labelMessage.preferredMaxLayoutWidth = CGRectGetWidth(labelMessage.frame);
}

UiTableViewHeader - Dynamic button event handler

I need to add a uiButton to a static uitableview section header - I've made an attempt with the following -
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// you can get the title you statically defined in the storyboard
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
CGRect frame = tableView.bounds;
// create and return a custom view
#define LABEL_PADDING 10.0f
HeaderLabelStyling *customLabel = [[HeaderLabelStyling alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] ;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-60, 10, 50, 30)];
addButton.backgroundColor = [UIColor whiteColor];
addButton.titleLabel.textColor = [UIColor colorWithRed:240/255.0f green:118/255.0f blue:34/255.0f alpha:1.0f];
addButton.titleLabel.tintColor = [UIColor blackColor];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
title.text = #"iawn";
customLabel.text = sectionTitle;
customLabel.backgroundColor= [UIColor colorWithRed:143.0f/255.0f green:137.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
customLabel.textColor = [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f];
[customLabel addSubview:addButton];
[addButton addSubview:title];
[addButton addTarget:self action:#selector(receiverButtonClicked:) forControlEvents:UIControlEventTouchDown];
return customLabel;
}
-(void)receiverButtonClicked:(id)sender{
NSLog(#"button clicked");
}
the above adds a button - but doesn't react to the click event - can anyone suggest how I can get this to work?
UILabel does not handles touches by default.
Add following line of code:
customLabel.userInteractionsEnabled = YES;
In order to display button only for third section you should add following condition:
if(section == 2){...}
So your -tableView:viewForHeaderInSection: should look as follows:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection (NSInteger)section {
if(section != 2) return nil;
// you can get the title you statically defined in the storyboard
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
CGRect frame = tableView.bounds;
// create and return a custom view
#define LABEL_PADDING 10.0f
HeaderLabelStyling *customLabel = [[HeaderLabelStyling alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] ;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-60, 10, 50, 30)];
addButton.backgroundColor = [UIColor whiteColor];
addButton.titleLabel.textColor = [UIColor colorWithRed:240/255.0f green:118/255.0f blue:34/255.0f alpha:1.0f];
addButton.titleLabel.tintColor = [UIColor blackColor];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
title.text = #"iawn";
customLabel.text = sectionTitle;
customLabel.backgroundColor= [UIColor colorWithRed:143.0f/255.0f green:137.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
customLabel.userInteractionsEnabled = YES;
customLabel.textColor = [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f];
[customLabel addSubview:addButton];
[addButton addSubview:title];
[addButton addTarget:self action:#selector(receiverButtonClicked:) forControlEvents:UIControlEventTouchDown];
return customLabel;
}

Header in section

I'm trying to copy the header in section, shown in this picture:
I' trying to add a label and the separator line inside the same view.
So far I have this code that isn't working at all...
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect sepFrame = CGRectMake(0, 50-1, 320, 1);
UIView *customView = [[UIView alloc] initWithFrame:sepFrame];
customView.backgroundColor = [UIColor colorWithWhite:224.0/255.0 alpha:1.0];
UILabel *sectionHeader = [[UILabel alloc] initWithFrame:CGRectNull];
sectionHeader.backgroundColor = [UIColor whiteColor];
sectionHeader.textAlignment = NSTextAlignmentCenter;
sectionHeader.font = [UIFont boldSystemFontOfSize:16];
sectionHeader.textColor = [UIColor colorWithRed:(66/255.0) green:(139/255.0) blue:(18/255.0) alpha:1] ;
//sectionHeader.text = [NSString stringWithFormat:#"Section %d", section];
switch (section) {
case 0:
sectionHeader.text =NSLocalizedString(#"ACTIVO", nil) ;
[customView addSubview:sectionHeader];
break;
case 1:
sectionHeader.text = NSLocalizedString(#"PASSIVO",nil);
[customView addSubview:sectionHeader];
break;
}
return customView;
}
Any help will be much appreciated since I'm new to IOS, thanks in Advance.
the following code should accomplish what you want (including the line on the bottom):
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
customView.backgroundColor = [UIColor colorWithWhite:224.0/255.0 alpha:1.0];
UILabel *sectionHeader = [[UILabel alloc] initWithFrame:customView.frame];
sectionHeader.backgroundColor = [UIColor clearColor];
sectionHeader.textAlignment = NSTextAlignmentCenter;
sectionHeader.font = [UIFont boldSystemFontOfSize:16];
sectionHeader.textColor = [UIColor colorWithRed:(66/255.0) green:(139/255.0) blue:(18/255.0) alpha:1];
sectionHeader.text = NSLocalizedString(section == 0 ? #"ACTIVO" : #"PASSIVO", nil);
[customView addSubview:sectionHeader];
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, customView.frame.size.height - 1, customView.frame.size.width, 1)];
lineView.backgroundColor = [UIColor colorWithRed:(66/255.0) green:(139/255.0) blue:(18/255.0) alpha:1];
[customView addSubview:lineView];
return customView;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect sepFrame = CGRectMake(0, 50-1, 320, 44); //FIX THIS
UIView *customView = [[UIView alloc] initWithFrame:sepFrame];
customView.backgroundColor = [UIColor colorWithWhite:224.0/255.0 alpha:1.0];
UILabel *sectionHeader = [[UILabel alloc] initWithFrame:sepFrame]; //FIX THIS
sectionHeader.backgroundColor = [UIColor whiteColor];
sectionHeader.textAlignment = NSTextAlignmentCenter;
sectionHeader.font = [UIFont boldSystemFontOfSize:16];
sectionHeader.textColor = [UIColor colorWithRed:(66/255.0) green:(139/255.0) blue:(18/255.0) alpha:1] ;
//sectionHeader.text = [NSString stringWithFormat:#"Section %d", section];
switch (section) {
case 0:
sectionHeader.text =NSLocalizedString(#"ACTIVO", nil) ;
break;
case 1:
sectionHeader.text = NSLocalizedString(#"PASSIVO",nil);
break;
}
[customView addSubview:sectionHeader];
return customView;
}
You need to give proper frames to your UI Element. Look for "//FIX THIS" in above code.
Try to use this method
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
CGRect sepFrame = CGRectMake(0, 50-1, 320, 50); // change here your view's height
UIView *customView = [[UIView alloc] initWithFrame:sepFrame];
customView.backgroundColor = [UIColor colorWithWhite:224.0/255.0 alpha:1.0];
UILabel *sectionHeader = [[UILabel alloc] initWithFrame:sepFrame]; // also change here in label frame
sectionHeader.backgroundColor = [UIColor whiteColor];
sectionHeader.textAlignment = NSTextAlignmentCenter;
sectionHeader.font = [UIFont boldSystemFontOfSize:16];
sectionHeader.textColor = [UIColor colorWithRed:(66/255.0) green:(139/255.0) blue:(18/255.0) alpha:1] ;
//sectionHeader.text = [NSString stringWithFormat:#"Section %d", section];
switch (section) {
case 0:
sectionHeader.text =NSLocalizedString(#"ACTIVO", nil) ;
[customView addSubview:sectionHeader];
break;
case 1:
sectionHeader.text = NSLocalizedString(#"PASSIVO",nil);
[customView addSubview:sectionHeader];
break;
}
return customView;
}
// and also write this method
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 50;
}
Take a look at the documentation for:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
It states that you must also implement:
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
for it to work properly.

UICollectionView poor scrolling performance

The problem I encounter is that whenever a row goes out of view, the scroll has a very fast and short lag.
This is my code:
- (UICollectionViewCell *)collectionView:(UICollectionView *)_collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [self.collView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
Saints *note = nil;
int aX=0;
int aY=0;
note = [self.fetchedResultsController objectAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews) {
if([view isKindOfClass:[UIImageView class]])
{
[view removeFromSuperview];
}
else if([view isKindOfClass:[UILabel class]])
{
[view removeFromSuperview];
}}
cell.backgroundColor = [UIColor clearColor];
UIImage *imgbackground = [UIImage imageNamed:#"today-left-side-images-bg.png"];
NSArray *messages = [[NSArray alloc] initWithObjects: #"random-saint-text-bg-brown.png",#"random-saint-text-bg-brightblue.png",#"random-saint-text-bg-green.png",#"random-saint-text-bg-grey.png",#"random-saint-text-bg-lightblue.png",#"random-saint-text-bg-lime.png",#"random-saint-text-bg-purple.png",#"random-saint-text-bg-red.png",#"random-saint-text-bg-teal.png",nil];
int randNum = arc4random() % [messages count];
NSString *returnValue = [messages objectAtIndex:randNum];
NSString *rndBGImg= returnValue;
UIImage *imgbackgroundlower = [UIImage imageNamed:rndBGImg];
UIImageView *imgViewlower = [[UIImageView alloc] initWithImage:imgbackgroundlower];
//imgViewlower.frame=CGRectMake(aX, aY+140, 140,73);
imgViewlower.frame=CGRectMake(aX+4, aY+114, 119,43);
UIImageView *imgView = [[UIImageView alloc] initWithImage:imgbackground];
imgView.frame=CGRectMake(aX, aY, 127,162);
UIImageView *imgSaintPic = [[UIImageView alloc]init];
imgSaintPic.tag=1;
imgSaintPic.frame=CGRectMake(aX+6, aY+6, 114,145);
//NSString *imgname = [aDic objectForKey:#"saint_image"];
NSString *imgname = note.saint_imagethumbnail;
UIImage *tempimg= [UIImage imageNamed:imgname];
[imgSaintPic setImage:tempimg];
UILabel *lblNamelocal=[[UILabel alloc]init];
NSString *strSaintName=note.saint_name;
//lblNamelocal.text=strSaintName;
if([note.saint_title length]>1)
lblNamelocal.text=[NSString stringWithFormat:#"%# %#",note.saint_title,strSaintName];
else
lblNamelocal.text=[NSString stringWithFormat:#"%#",strSaintName];
//lblNamelocal.frame = CGRectMake(aX+6, aY+109, 116,30);
[lblNamelocal sizeToFit];
lblNamelocal.frame = CGRectMake(aX+5, aY+115, 118,26);
lblNamelocal.lineBreakMode = UILineBreakModeWordWrap;
lblNamelocal.numberOfLines = 0;
lblNamelocal.backgroundColor = [UIColor clearColor];
lblNamelocal.textColor = [UIColor whiteColor];
lblNamelocal.font = [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:11 ];
// lblNamelocal.textAlignment=UITextAlignmentLeft;
lblNamelocal.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
lblNamelocal.shadowColor = [UIColor darkGrayColor];
lblNamelocal.shadowOffset = CGSizeMake(0,0.5);
lblNamelocal.textAlignment = UITextAlignmentCenter;
UILabel *lblsubtitle=[[UILabel alloc]init];
//NSString *strSaintSubtitle=[aDic objectForKey:#"saint_title"];
lblsubtitle.text=note.saint_subtitle;
//lblsubtitle.frame = CGRectMake(aX+6, aY+132, 116, 25);
lblsubtitle.frame = CGRectMake(aX+5, aY+140, 113, 20);
lblsubtitle.lineBreakMode = UILineBreakModeWordWrap;
lblsubtitle.numberOfLines = 2;
lblsubtitle.backgroundColor = [UIColor clearColor];
lblsubtitle.textColor = [UIColor whiteColor];
lblsubtitle.font = [UIFont fontWithName:#"HelveticaNeue" size:10];
// Removed CJamesRun lblsubtitle.textAlignment=UITextAlignmentLeft;
lblsubtitle.shadowColor = [UIColor darkGrayColor];
lblsubtitle.shadowOffset = CGSizeMake(0,0.5);
lblsubtitle.textAlignment = UITextAlignmentCenter;
imgViewlower.tag=3;
lblNamelocal.tag=2;
lblsubtitle.tag=4;
[cell.contentView addSubview:imgView];
[cell.contentView addSubview:imgSaintPic];
[cell.contentView addSubview:imgViewlower];
[cell.contentView addSubview:lblNamelocal];
[cell.contentView addSubview:lblsubtitle];
// cell.layer.masksToBounds = NO;
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
What I've tired is to rasterize the cell layer, and also to remove the views from the SuperView upon creating a new cell.
Any other suggestions?
I would recommend setting up your cells' subviews just once, and then only updating the contents inside collectionView:cellForItemAtIndexPath:. E.g. you're loading some images in each cell, but those are the same for every cell, so loading them every time the cell is reused is unnecessary.

Why does sizeToFit remove my entire label?

I am trying to use the function sizeToFit. It works perfectly throughout the application however it does not work in the code below. Further to that, if it can't be done the way I am doing it please advise.
self.label = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 67.0, 290, 50)];
self.label.font= [UIFont fontWithName:#"Helvetica-Bold" size:20];
self.label.textColor = [UIColor colorWithRed:33.0f/255.0f green:74.0f/255.0f blue:146.0f/255.0f alpha:1.0f];
self.label.numberOfLines = 0;
self.label.lineBreakMode = NSLineBreakByWordWrapping;
self.label.backgroundColor = [UIColor whiteColor];
[self.contentView addSubview:self.label];
self.description = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 380.0, 300, 400)];
self.description.font= [UIFont fontWithName:#"Helvetica-Light" size:15];
self.description.textColor = [UIColor blackColor];
self.description.textAlignment = NSTextAlignmentJustified;
self.description.numberOfLines = 0;
self.description.lineBreakMode = NSLineBreakByWordWrapping;
self.description.backgroundColor = [UIColor whiteColor];
[self.description sizeToFit];
[self.contentView addSubview:self.description];
self.image = [[UIImageView alloc] initWithFrame:CGRectMake(20, 130, 280, 228)];
self.image.clipsToBounds = YES;
//[scrollView addSubview:self.image];
[self.contentView addSubview:self.image];
self.backgroundColor = [UIColor whiteColor];
I passed the data using this method from a different controller
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
Cell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
NSDictionary *item = [_articleListmain objectAtIndex:indexPath.item];
// set the article image
[cell.image setImageWithURL:[item objectForKey:#"image"]];
[cell.label setText:[item objectForKey:#"title"]];
[cell.description setText:[item objectForKey:#"description"]];
return cell;
}
Since the label is empty, sizeToFit shrinks it down to nothing. That's the point. Set some text then call sizeToFit and the label will be just big enough for the text.
I encountered the same problem. I have a customized cell and a separated tableview controller. it turns out that we should set the NumberOfLines and SizeToFit in the controller, not the cell.

Resources