Can we set backgroundImage for Section in UITableview? - cocoa-touch

Can we set Background image for UITableView Section like UITableViewCell backGroundView. As per my research Its not possible & we need to customize the row like section of it.
Cane we able to get better solution apart from this.
Thanks in advance!

In case anyone are still interrested, there is actually a pretty straigt forward solution to this. UITableView will tell you the frames of each of your sections using the selector rectForSection:
Adding a backgroud image to each section would then look something like this (Somewhere in the view controller):
for(int i = 0;i < [self numberOfSectionsInTableView:self.tableView]; i++) {
UIImage *img = [[UIImage imageNamed:#"background"] resizableImageWithCapInsets:UIEdgeInsetsMake(30.0, 30.0, 40.0, 40.0) ]; //In this example the image is stretchable
UIView *borderView = [[UIImageView alloc] initWithImage:img];
CGRect section_rect = [self.tableView rectForSection:i];
borderView.frame = section_rect;
[self.tableView addSubview:borderView];
}
Just remember that if you reload the data in the tableview you would have to redo this as well.

Yes, I am doing this by following way, I think it work for you also,....
-(void)addBackgroundViewForSectionIndex:(int)tagIndex {
for (UIView * subview in tableView.subviews) {
if(subview.tag == tagIndex)
[subview removeFromSuperview];
}
CGRect sectionFrame = [tableView rectForSection:tagIndex];
UIImageView *newView = [[UIImageView alloc]initWithFrame:sectionFrame];
newView.tag = tagIndex;
[newView setImage:[UIImage imageNamed:#"image.PNG"]];
[tableView addSubview:newView];
[tableView sendSubviewToBack:newView];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [collection objectAtIndex:indexPath.row];
[self addBackgroundViewForSectionIndex:indexPath.section];
return cell;
}
Let me know if any issue,...:)

No, this is not possible using UITableView as it was intended. Section headers, as others have suggested, won't work because they'll only be visible while the header is visible. As soon as it disappears while scrolling up, the background image would disappear.
Your two options are:
Add UIImageView instances directly as subviews to the table view. Not fun, as you'll have to size and position them manually, which is kind of hard to do.
Use UICollectionView, which supports decoration views (exactly what you're looking for).
The UICollectionView method is probably better, but to be honest, either option would require a lot of work.

Swift 5 bare-bones implementation of Jesper's answer.
for sectionIndex in 0..<tableView.numberOfSections {
let backgroundView = UIView() // replace UIView with anything else you want, whether it was UIImage, nibView, etc...
backgroundView.frame = tableView.rect(forSection: sectionIndex)
tableView.addSubview(backgroundView)
}

You can set the Background for Section of TableView.
Have a look at delegate method as below:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIImageView *bgImgView = [[[UIImageView alloc] initWithFrame:CGRectMake(0.0,0.0,tableView.bounds.size.width,40.0)] autorelease];
bgImgView.image = [UIImage imageNamed:#"yourimage.jpg"];
return bgImgView;
}
Hope this will be helpful to you.
Cheers!

table= [[UITableView alloc] initWithFrame:CGRectMake(7,0, 307, 124) style:UITableViewStylePlain];
[table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tablebg_pt12.png"]];
imageView.frame=CGRectMake(0, 0, 307, 124);
imageView.image= [UIImage imageNamed:#"tablebg_pt12.png" ];
table.backgroundView = imageView;
[imageView release];
table.delegate = self;
table.dataSource = self;
// table.backgroundColor=[UIColor clearColor];
[viewTable addSubview:table];

Related

Loading UITableViewCell from xib results in loaded the nib but the view outlet was not set

I'm trying to create a UITableViewController that it's UITableViewCell is a xib file. The Xib file is empty (0 controls) all the controls are created programmatically like this
- (id) initWithTitle: (NSString*)p_title andImage: (UIImage*)p_image
{
//adding checkbox & title
MMCheckbox* myCheckbox = [[MMCheckbox alloc] initWithTitle:p_title andHeight:20];
myCheckbox.frame = CGRectMake(self.frame.size.width - myCheckbox.frame.size.width -15,20, myCheckbox.frame.size.width, 20);
myCheckbox.flat = YES;
myCheckbox.strokeColor = [UIColor whiteColor];
myCheckbox.checkColor = [UIColor magentaColor];
myCheckbox.uncheckedColor = [UIColor clearColor];
myCheckbox.tintColor = [UIColor clearColor];
[self addSubview:myCheckbox];
//adding the image
UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake (15, 10, 20, 20)];
[imageView setImage: p_image];
return self;
}
In the xib file I placed a UITableViewCell and set it's class to my class MMCheckboxTableViewCell
In my tableViewController I'm creating the cell loading it from NIB like so
- (UITableViewCell *)tableView:(UITableView *)p_tableView cellForRowAtIndexPath:(NSIndexPath *)p_indexPath
{
//create a UI tableViewCell
UITableViewCell* cell = [p_tableView
dequeueReusableCellWithIdentifier:#"comboBoxCell"];
if(cell == nil)
{
UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:#"MMComboBoxTableCell" bundle:nil];
// Grab a pointer to the custom cell.
cell = (MMComboBoxTableCell *)temporaryController.view;
}
}
I've looked at many post with the same question and checked to see I've got every thing right according to this.
Please let me know what I'm missing.
My problem was with the way I was loading the XIB.
By changing the following:
UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:#"MMComboBoxTableCell" bundle:nil];
to this:
MMComboBoxTableCell* temporaryController = [[[NSBundle mainBundle] loadNibNamed:#"MMComboBoxTableCell" owner:self options:nil] objectAtIndex:0];
Problem solved.

How to change the bounce-region's color/background for a horizontal UITableView

I'm working on a custom "Pulse style" UITableView according to this tutorial, and everything is going great. I've made some modifications and extensions but there is one feature I'd like to implement that I need some help with: the color of the horizontal bounce regions.
This is the method that creates my cell with a table view in it:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = [#"TableViewCell" stringByAppendingFormat:#"%i", self.content.indexInArrayOfViews];
UIView *view = [self.content viewAtIndex:indexPath.row];
UITableViewCell *cell = [self.horizontalTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
view.center = CGPointMake(view.center.y,view.center.x);
view.contentMode = UIViewContentModeCenter;
view.transform = CGAffineTransformMakeRotation(M_PI_2);
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell addSubview:view];
return cell;
}
I'm aware there is a reuse cell issue, but for right now I want to change this color here [IMG].
I can control the color of the vertical table view bounce areas, but I am having difficulty replicating this success for my horizontal view.
This is how I do it vertically:
CGRect frame = self.tableView.bounds;
frame.origin.y = -frame.size.height;
UIView* topBack = [[UIView alloc] initWithFrame:frame];
topBack.backgroundColor = [self.delegate backgroundColorForTopOfTableView];
[self.tableView addSubview:topBack];
[topBack release];
This was according to this StackOverflow question.
How do I change the color/background of my horizontal table view (which is nested in a table view cell)?
Here is an album with some relevant iPhone screenshots and IB screenshots.
I discovered a solution:
if (indexPath.row == 0){
UIView *bounce = [[UIView alloc] initWithFrame:CGRectMake(-320, 0, 320, 150)];
bounce.backgroundColor = [self.delegate colorForBounceRegionAtRow:self.content.indexInArrayOfViews];
[view addSubview:bounce];
}
if (indexPath.row + 1 == self.content.viewCount){
UIView *bounce = [[UIView alloc] initWithFrame:CGRectMake([self.content widthOfViewAtIndex:self.content.viewCount - 1], 0, 320*2, [self.content greatestHeight])];
bounce.backgroundColor = [self.delegate colorForBounceRegionAtRow:self.content.indexInArrayOfViews];
[view addSubview:bounce];
}
This adds a full screen's worth of colored rectangle to the first and last elements, giving the illusion of a bounce region.

add project with app delegate

I'm trying to add a dynamic horizontal scroll to a table cell.
I found an example after searching for a while, but since the example project only was the view it was directly connected to the app delegate which contained the majority of the relevant code. Most of it within applicationDidFinishLaunching.
Do any of you know how I am supposed to add this code to my project?
Thanks in advance, Tom
EDIT:
Here's the link to the sample project i downloaded: http://blog.sallarp.com/wp-content/uploads/2008/11/slidemenu.zip
Here's the youtube clip of how it's supposed to work: http://www.youtube.com/watch?v=wFqBNXZ4SHI
EDIT 2 (New code):
"famorables" is declared with 5 one-word-strings
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MyFamorablesCell";
UITableViewCell *cell;
//Create Cell
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//Create a UIScroll View
UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80)];
scrollview.contentSize = CGSizeMake(self.view.frame.size.width * 2, 80);
scrollview.showsHorizontalScrollIndicator = NO;
float totalButtonWidth = 0.0f;
famorableArray = self.famorables;
for(int i = 0; i < [self.famorables count]; i++){
UIButton *famorableButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[famorableButton setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 30.0f)];
[famorableButton setTitle:[NSString stringWithFormat:#"%#", [famorableArray objectAtIndex:[indexPath row]]] forState:UIControlStateNormal];
// Move the buttons position in the x-demension (horizontal).
CGRect btnRect = famorableButton.frame;
btnRect.origin.x = totalButtonWidth;
[famorableButton setFrame:btnRect];
// Add the button to the scrollview
[scrollview addSubview:famorableButton];
// Add the width of the button to the total width.
totalButtonWidth += famorableButton.frame.size.width;
}
[cell.contentView addSubview:scrollview];
return cell;
}
Okay Try this
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
//Create Cell
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
//Create a UIScroll View
UIScrollView scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, (it will be the height of the Cell u want))];
scrollview.contentSize = CGSizeMake(self.view.frame.size.width * 2,(it will be the height of the Cell u want));
scrollview.showsHorizontalScrollIndicator = NO;
/*
Now add every this u might want to add in ur Scroll view.
keep that in mind that the height and width of contentSize and ScrollView will be depandent on ur requirement
Make sure u add every thing u want in the Scroll view will be the part of Scroll View
like for label
//Add Something to Scroll View
[scrollView addSubview:label];
*/
//Add Scroll view to Cell
[cell.contentView addSubview:scrollView];
return cell;
}
This will Work
In case of any queries feel free to ask

Custom UITableViewCell does not appear on second load

I have a custom uitableview with custom uitableviewcell in my view cell. The cell doesn't show on second load. That is, when I go from this view to another and back to this view.
This is how I load my table in my view.
CropTableViewController *cropTblViewCon = [[CropTableViewController alloc]init];
self.cropTableViewController = cropTblViewCon;
cropTableViewController.view.frame = cropTblView.frame;
[cropTblView removeFromSuperview];
[self.view addSubview:cropTableViewController.view];
self.cropTblView = cropTableViewController.tableView;
This is how I go another view
AppDelegate_iPhone *appDelegate = [[UIApplication sharedApplication] delegate];
AddPestReportStepOne *report = [[AddPestReportStepOne alloc]init];
[appDelegate.navCon pushViewController:report animated: YES];
[report release];
This is how I load my table cell in my custom table view.
static NSString *CellIdentifier = #"CustomCropCell";
CustomCropCell *cell = (CustomCropCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
tableView.scrollEnabled = NO;
// tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:#"CustomCropCell" owner:nil options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (CustomCropCell *) currentObject;
break;
}
}
}
//if (counter<6 ) {
CropEntity *crop = [[CropEntity alloc] init];
crop=[ cropList objectAtIndex:counter];
NSString *imgStr = [NSString stringWithFormat:#"%#%#%#",domainName,cropImagePath, [crop cropImage]];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgStr]]];
CGSize size = CGSizeMake(80, 80);
[cell setBackgroundColor: [UIColor clearColor]];
image = [Utilities scale:image toSize:size ];
[cell.columnOne setTag: [[crop cropId] integerValue] ];
[cell.columnOne setTitle:[crop cropName] forState:UIControlStateNormal];
[cell.columnOne setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.columnOne setTitleEdgeInsets:UIEdgeInsetsMake(0.0, -image.size.width, -75.0, 0.0)]; // Left inset is the negative of image width. counter = counter+ 1;
[cell.columnOne setImage:image forState:UIControlStateNormal];
[cell.columnOne setImageEdgeInsets:UIEdgeInsetsMake(-15.0, 0.0, 0.0, -cell.columnOne.titleLabel.bounds.size.width)]; // Right inset is the negative of text bounds width.
[cell.columnOne setBackgroundColor: [UIColor clearColor]];
counter = counter + 1;
It seems that the rows are not removed. My cellforrowat indexpath keep increasing...
Okay, i'm assuming you want to add a UITableView to a ViewController. Here are the steps for this:
(1) You have create an UIViewController, whether by code or interface builder
(2) Create an UITableView, and add it to your UIViewController
UITableView *tableView = [[UITableView alloc]
initWithFrame:CGRectMake(0, 0, 320, 440)
style:UITableViewStylePlain];
// Set up the tableView delegate and datasource
[self.view addSubview:tableView];
[tableView release];
I'm sure there is a reason why you are adding the tableView to a UIViewController (there is not reason to have an extra UITableViewController. If not just use a UITableViewController, and set up a UITableView.
Also, keep in mind where you create the tableView at. For instance, if you create it in init or viewDidLoad and using a UINavigationController, when you hit the back button on the UINavigationController the ViewDidLoad or init isn't getting called. Try it yourself, put a NSLog statement to test.
So either use viewDidAppear or [tableView reloadData];
Edit:
Think about your code you create a UITableViewContoller then you remove its UITableView from it's super view (does not make sense) and then you add the UITableViewControllers view (the UITableView) to self.view which is i'm guessing a UIViewController. Surely this can't be what you are trying to do.
I would recommend reading Apple's View Programming guide for a better understanding of UIViewControllers and Views.
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaViewsGuide/Introduction/Introduction.html

UITableViewCell with images in different dimensions

I'm trying to use my ReusableCell for cells with images in different dimensions. The images are put inside a 220x150 black box with with scaling UIViewContentModeScaleAspectFit.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NewsTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NewsItem *item = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:item.imageUrl]];
[cell.imageView setImage:[[UIImage alloc] initWithData:data]];
[cell.imageView setBackgroundColor:[UIColor blackColor]];
[cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
CGRect imageViewFrame = cell.imageView.frame;
imageViewFrame.size.width = 220;
imageViewFrame.size.height = 150
[cell.imageView setFrame:imageViewFrame];
[cell.textLabel setText:item.title];
return cell;
}
The above code results in a layout like below and the images are sometimes changing when scrolling in the table view.
Instead of this unstructured layout, I would like the images to be aligned like this:
What am I doing wrong with this ReusableCell?
EDIT1:
I'm trying to create an imageView and add this imageView as a superview to cell.contentView.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NewsTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NewsItem *item = [self.fetchedResultsController objectAtIndexPath:indexPath];
UIImage *placeholderImage = [UIImage imageNamed:#"ImagePlaceholderThumb"]; //220x150
UIImageView *imageView = [[UIImageView alloc] initWithImage:placeholderImage];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:item.imageUrl]];
[imageView setImage:[[UIImage alloc] initWithData:data]];
[imageView setBackgroundColor:[UIColor blackColor]];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
CGRect imageViewFrame = imageView.frame;
imageViewFrame.size.width = placeholderImage.size.width;
imageViewFrame.size.height = placeholderImage.size.height;
[imageView setFrame:imageViewFrame];
[cell.contentView addSubview:imageView];
[cell.textLabel setText:item.title];
return cell;
}
The above code results in the following:
It is like some of the images are visible in two cells. It seems that they are not keeping the size I've set in the imageViewFrame. Do you know why?
A quick fix would be using content mode UIViewContentModeScaleAspectFill. Images will be stretched in one or both dimensions to fill up the whole image view bounds.
You really need subclassing UITableViewCell to do this right.
Thre is a lazy solution adding a new UIImageView and using a spacer, as Keller told you in his answer (feel free to accept his answer, this is just the missing code).
Extract of tableView:cellForRowAtIndexPath::
...
cell.textLabel.text = [NSString stringWithFormat:#"Cell #%i", indexPath.row];
cell.imageView.image = [UIImage imageNamed:#"spacer.png"]; /* spacer is 64 x 44 */
/* image view width should be ~ 64 px, otherwise it will overlap the text */
UIImageView *iv = [[UIImageView alloc] initWithFrame:(CGRect){.size={64, tableView.rowHeight}}];
switch (indexPath.row) {
case 0:
iv.image = [UIImage imageNamed:#"waterfall.png"];
break;
/* etc... */
}
if (indexPath.row < 3) {
/* add black bg to cell w/ images */
iv.backgroundColor = [UIColor blackColor];
}
iv.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:iv];
...
The table will look like this:
You need to set the placeholder (spacer.png above) in the existing cell image view. It will push the text label to the right.
You can use aspect fill and remove the background color bit:
iv.contentMode = UIViewContentModeScaleAspectFill;
The table will look wrong because the image is drawn outsite the bounds:
Just clip to bounds to get a better result:
iv.clipsToBounds = YES;
Create a UIImageView subview for each cell and it to the contentView. Each UIImageView contains an image with a consistent frame but with option UIViewContentModeScaleAspectFit. Then just Set the background color of the UIImageView to black.
I just confirmed this works, but you need to also create a placeholder spacer image to make sure the textLabel moves out of the way. Just make it the same dimensions of your image (with the letter boxing).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//spacer
cell.imageView.image = [UIImage imageNamed:#"placeholder"];
//imageview
UIImageView *thumbnail = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
thumbnail.tag = kThumbTag;
thumbnail.backgroundColor = [UIColor blackColor];
thumbnail.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:thumbnail];
}
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"Cell %d", indexPath.row];
cell.imageView.frame = CGRectMake(0, 0, 80, 44);
UIImageView *thumb = (UIImageView*)[cell.contentView viewWithTag:kThumbTag];
if (indexPath.row == 0) {
[thumb setImage:[UIImage imageNamed:#"image1.png"]];
} else {
[thumb setImage:[UIImage imageNamed:#"image2.png"]];
}
return cell;
}
Obviously, this example isn't lazy loading the images (I didn't realize you were loading them from a URL). For that, I would use a subclass with EGOImageView or something of the like.