I have created custom buttons for each viewcell(1 per cell). When scrolling the UITableView some viewcells have 2 buttons and that was not intended. I fail to see the error in my ways.
Please help!
Image: http://s18.postimg.org/v7djg84ah/buttons_App.png
Header:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource>
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section;
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
-(void)checkboxSelected:(id)sender;
#end
Implementation
#import "ViewController.h"
#define sectionCount 1
#define itemSection 0
#interface ViewController ()
{
NSArray *items;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
items = #[#"itemdd", #"item2",#"itemdd", #"item2",#"itemdd", #"item2",#"itemdd", #"item2",#"itemdd", #"item2",#"itemdd", #"item2",#"itemdd", #"item2",#"itemdd", #"item2",#"itemdd", #"item2",#"itemdd", #"item2"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return sectionCount;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch(section)
{
case itemSection:
{
return [items count];
}
default:
return 0;
}
}
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
switch (section)
{
case itemSection:
return #"Items";
default:
return #"woot";
}
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:#"itemCell"];
switch(indexPath.section)
{
case itemSection:
cell.textLabel.text = items[indexPath.row];
break;
default:
cell.textLabel.text=#"Unknown";
}
NSInteger x,y;
x =cell.frame.origin.x +100; y = cell.frame.origin.y + 10;
UIButton *checkbox;
checkbox = [[UIButton alloc] initWithFrame:(CGRectMake(x,y,20,20))];
[checkbox setBackgroundImage:[UIImage imageNamed:#"notSelectedButton.png"]forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:#"checkedButton.png"]forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:#"uncheckedButton.png"]forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted = YES;
[checkbox addTarget:self action:#selector(checkboxSelected:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:checkbox];
return cell;
}
-(void)checkboxSelected:(id)sender
{
bool selected = [(UIButton *)sender isSelected];
if (selected)
{
[(UIButton *)sender setSelected:false];
}
else
{
[(UIButton *)sender setSelected:true];
}
}
#end
First, look at this statement in your code:
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:#"itemCell"];
The method -dequeueReusableCellWithIdentifier will either pull an already created table view cell, or generate a new one if no reusable cell is available.
Now review this statement:
checkbox = [[UIButton alloc] initWithFrame:(CGRectMake(x,y,20,20))];
…
[cell.contentView addSubview:checkbox];
If your cell was just initialized, this code works fine. However, when you scroll your table, your code will start pulling old table view cells that were thrown into the reusable queue. Those old table view cells already contain a UIButton. So every time you call -addSubview: on an old cell, you add duplicate buttons.
There are many ways to fix this. Here's one solution for you:
static NSInteger const checkboxTag = 123;
checkbox = (UIButton *)[cell.contentView viewWithTag:checkboxTag];
if (!checkbox) {
checkbox = [[UIButton alloc] initWithFrame:(CGRectMake(x,y,20,20))];
checkbox.tag = checkboxTag;
[checkbox setBackgroundImage:[UIImage imageNamed:#"notSelectedButton.png"]forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:#"checkedButton.png"]forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:#"uncheckedButton.png"]forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted = YES;
[checkbox addTarget:self action:#selector(checkboxSelected:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:checkbox];
}
EDIT:
Something else worth pointing out. This statement:
x =cell.frame.origin.x +100; y = cell.frame.origin.y + 10;
By referencing cell.frame, you're creating a UIButton relative to the cell's position in the table view, not the cell itself. Set x = 100; y = 10; to make the offset relative to the the cell's bounds instead.
Related
i have a edit button and delete button. when edit button tap table view set editing mode on from left side of table view.i already do this. but when select row and tap to the delete button how to use this method
[self.tableView deleteRowsAtIndexPaths=#"indexpath" withRowAnimation:UITableViewRowAnimationAutomatic];
i can delete data but can not use this method from delete method. i need it because after delete button tap, set editing mode gone, and table view update with animation. if i reload table view its not animated.
Try this
-(void)onButtonTap:(UIButton *)sender {
UITableViewCell *cell = (UITableViewCell *)sender.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
int index = indexPath.row;
[arrDataSource removeObjectAtIndex:index];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
}
I created Custom Button Edit and Delete with action.Delete button deletes the row successfully.It works fine.I worked with sample one for your question.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
#property (strong, nonatomic) IBOutlet UITableView *tableViewDeleterow;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrTableData;
}
#end
#implementation ViewController
#synthesize tableViewDeleterow;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrTableData = [[NSMutableArray alloc]initWithObjects:#"iPhone",#"iPad",#"iTV",#"iWatch",nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//UITableView DataSource methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrTableData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
//Custom Edit Button
UIButton *btnEdit = [UIButton buttonWithType:UIButtonTypeCustom];
btnEdit.frame = CGRectMake(0,4,100, 20);
[btnEdit setTitle:#"Edit" forState:UIControlStateNormal];
[btnEdit setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[btnEdit addTarget:self action:#selector(actionEdit:) forControlEvents:UIControlEventTouchUpInside];
btnEdit.tag = indexPath.row;
[cell.contentView addSubview:btnEdit];
//Custom Delete Button
UIButton *btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
btnDelete.frame = CGRectMake(250,4,100, 20);
[btnDelete setTitle:#"Delete" forState:UIControlStateNormal];
[btnDelete setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[btnDelete addTarget:self action:#selector(actionDelete:) forControlEvents:UIControlEventTouchUpInside];
btnDelete.tag = indexPath.row;
[cell.contentView addSubview:btnDelete];
return cell;
}
-(void)actionEdit:(UIButton *)sender
{
//do stuff here for edit action
}
-(void)actionDelete:(UIButton *)sender
{
UITableViewCell *cell = (UITableViewCell*) sender.superview.superview;
NSIndexPath *indexPath = [tableViewDeleterow indexPathForCell:cell];
NSLog(#"The selected indexPath.row is - %ld",(long)indexPath.row);
[arrTableData removeObjectAtIndex:indexPath.row];
[tableViewDeleterow deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
}
#end
When I delete the 2nd index path delete row,the printed result is
The selected indexPath.row is - 2
At intial
After deleting the second index path row delete button
I want to add button inside UITableView with drag and drop but i don't know how to call them inside UITableviewCell.You can see a keyword Desc where I have to set them as button title so that I can get all values which I placed in coreData frameWork.
-(void)setquestions:(int)qid
{
NSManagedObject *singleobject = nil;
singleobject = AllQuestions[qid];
NSString * desc=[singleobject valueForKey:#"questionDesc"];
questionlabel.text=desc;
int qidns=[[singleobject valueForKey:#"questionId"]intValue];
NSArray *dummy=[self getoptions:qidns];
NSLog(#"--inside setquestion-%lu",(unsigned long)dummy.count);
for (int i=0; i<dummy.count; i++) {
NSManagedObject *singleobject = nil;
singleobject = dummy[i];
NSString * desc=[singleobject valueForKey:#"optionDesc"];
[self addbutton:desc bid:i];
}
}
-(void)addbutton:(NSString *)desc bid:(int)bid{
[[QBFlatButton appearance] setFaceColor:[UIColor colorWithWhite:0.75 alpha:1.0] forState:UIControlStateNormal];
[[QBFlatButton appearance] setSideColor:[UIColor colorWithWhite:0.55 alpha:1.0] forState:UIControlStateNormal];
optionButton = [QBFlatButton buttonWithType:UIButtonTypeCustom];
optionButton.faceColor = [UIColor colorWithRed:0.400f green:0.737f blue:0.761f alpha:1.00f];
optionButton.sideColor = [UIColor colorWithRed:0.400f green:0.737f blue:0.761f alpha:1.00f];
optionButton.radius = 4.0;
optionButton.margin = 4.0;
optionButton.depth = 3.0;
[optionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
optionButton.titleLabel.font=[UIFont systemFontOfSize:12];
optionButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
optionButton.titleLabel.textAlignment = NSTextAlignmentCenter;
optionButton.tag=bid;
[optionButton setTitle:desc forState:UIControlStateNormal];
optionButton.frame = CGRectMake(5,bid*55,optionsview.frame.size.width-10, 50);
[optionsview addSubview:optionButton];
}
- (void)logItems {
int index = 0;
for ( NSString *str in self.items ) {
NSLog(#"%d: %#", index++, str);
}
}
#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:#"Cell"];
if ( cell == nil ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
return cell;
}
#pragma mark - Edit Mode
- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleNone; // No Delete icon
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
[table deselectRowAtIndexPath:indexPath animated:YES];
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Can move cell
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
NSUInteger origins = sourceIndexPath.row; // Original position
NSUInteger to = destinationIndexPath.row; // Destination position
NSLog(#"Origin %lu, To %lu", (unsigned long)origins, (unsigned long)to);
NSString *swap = [self.items objectAtIndex:origin];// Item
[swap shouldGroupAccessibilityChildren];
}
As I understood from the question you want to get the button in the cell for that you can create a custom cell class and then call this custom cell inside the cellforrow function. You can call the button like this
customCell.button.title = "some-string"
If you want a custom button with a particular action added to each of the cells, first you need to create a custom UI cell(using XIB since you need to drag and drop). Then add the button to that, and connect the button's IBAction and IBOutlet to the custom subclass for the cell. Next Add a protocol with a function to the cell subclass so that you can send a callback to the ViewController when the button is clicked. Now implement the delegate in the ViewController and use this cell for your purpose. If the delegate function returns the cell, you can figure out which cell's button is clicked, hence getting the indexpath to perform required action.
I have a tableview where I have 4 fields(Personal Info, Education, Hobbies, Interest). Now my requirement is when I tap on a cell, that cell will expand and there the detail of that cell will show.
As an example if I tap on Personal Info cell, that cell will expand and there the datas that will show is First Name, Last Name etc.
I have do to do this by using only one tableview.
Can anyone give me any idea how to do this. Any help is highly appreciated.
Here below is the code for that. With little modifications you can full fill your requirement.
NSArray *tableData;
static int selectedSection=10;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
isValueSelected=NO;
tableData=[[NSArray alloc]initWithObjects:#"Sivajee",#"Sri Ramana",#"Anusha",#"Hari Krishna",#"Manojna",#"Vamsi", nil];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
int numberofRows=0;
NSLog(#"%d",selectedSection);
if(selectedSection!=section)
{
return 0;
//numberofRows=[tableData count];
}
else
{
numberofRows=[tableData count];
return numberofRows;
//numberofRows=0;
}
//return numberofRows;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
if(cell==nil)
{
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text=[tableData objectAtIndex:indexPath.row];
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [tableData count];
}
//
/*
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return tableData;
}*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
[view setBackgroundColor:[UIColor redColor]];
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom ];
[button setTag:section];
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[tableData objectAtIndex:section] forState:UIControlStateNormal];
[button setFrame:CGRectMake(100, 0, 100, 20)];
[view addSubview:button];
return view;
}
-(void)buttonClicked:(id)sender
{
UIButton *but=(UIButton *)sender;
NSLog(#"sender tag is %d",but.tag);
isValueSelected=YES;
selectedSection=but.tag;
NSLog(#"%d",selectedSection);
[self.tblControll reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(selectedIndex == indexPath.row)
{
expanted row hight
}
else
{
normal row hight
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(selectedIndex == indexPath.row)
{
show all the label you want to show
}
else
{
hide the label you have to hid when in the normal position.
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
selectedIndex = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
I am new to Objective-C and Xcode so please bear with me.
I have tried to solve this problem for many days now and restraining myself from post. The number of posts I have read regarding UIButtons with Tableviews is a lot and I think I am too dumb to understand why this does not work.
I want to implement a tableview with multiple columns of checkboxes:
1 item1 checkbox checkbox
2 item2 checkbox checkbox
Keep in mind that I am currently trying to implement only 1 column of checkboxes.
I am using coded UIButton and setting their image to one of my images: checkedImage.png, unCheckedImage.png
One string NSArray #"" (with item title) and one NSMutableArray BOOL (value for if checked) for every item.
Problem:
A checked button #index 1-4 will lose its checked image upon scrolling the table view. Index 5 seems to stay put, others not so much.
When debugging the method: -(void)checkboxSelected:(id)sender seems to drag out the right #row(index) and the bool variable seems to be correct but image not.
My thought was that the UIButton changes state, so I implemented the buttonimage on all ControlState, no difference occurred.
Code:
#import "ViewController.h"
#define sectionCount 1
#define itemSection 0
#interface ViewController ()
{
NSArray *items;
NSMutableArray *itemsChecked;
UITableView *_tableView;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
items = #[#"1", #"2",#"3", #"4",#"5", #"6",#"7", #"8",#"9", #"10",#"11", #"12",#"13", #"14"];
itemsChecked = [[NSMutableArray alloc] init];
for(int i = 0; i < 14; i++)
{
[itemsChecked addObject:[NSNumber numberWithBool:false]];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
_tableView = tableView;
return sectionCount;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
switch(section)
{
case itemSection:
{
return [items count];
}
default:
return 0;
}
}
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
switch (section)
{
case itemSection:
return #"Items";
default:
return #"woot";
}
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:#"itemCell"];
switch(indexPath.section)
{
case itemSection:
cell.textLabel.text = items[indexPath.row];
break;
default:
cell.textLabel.text=#"Unknown";
}
static NSInteger checkboxTag = 123;
NSInteger x,y;x = 100; y = 10;
UIButton *checkbox = (UIButton *) [cell.contentView viewWithTag:checkboxTag];
if (!checkbox)
{
checkbox = [[UIButton alloc] initWithFrame:(CGRectMake(x,y,20,20))];
checkbox.tag = checkboxTag;
[cell.contentView addSubview:checkbox];
}
[checkbox setImage:[UIImage imageNamed:#"notSelectedButton.png"] forState:UIControlStateNormal];
checkbox.adjustsImageWhenHighlighted = YES;
[checkbox addTarget:self action:#selector(checkboxSelected:) forControlEvents:UIControlEventTouchDown];
return cell;
}
-(NSIndexPath *) GetCellFromTableView: (UITableView *)tableView Sender:(id)sender
{
CGPoint position = [sender convertPoint:CGPointZero toView:tableView];
NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:position];
return indexPath;//[tableView cellForRowAtIndexPath:indexPath];
}
-(void)checkboxSelected:(id)sender
{
NSIndexPath *ip = [self GetCellFromTableView:_tableView Sender:sender];
NSInteger row = ip.row;
bool checked = [[itemsChecked objectAtIndex:row] boolValue];
if (checked)
{
[(UIButton *)sender setSelected:false];
itemsChecked[row] = #NO;
checked = NO;
}
else
{
[(UIButton *)sender setSelected:true];
itemsChecked[row] = #YES;
checked = YES;
}
UIButton* checkbox = sender;
if (checked)
{
[checkbox setImage:[UIImage imageNamed:#"checkedButton.png"] forState:UIControlStateNormal];
[checkbox setImage:[UIImage imageNamed:#"checkedButton.png"] forState:UIControlStateDisabled];
[checkbox setImage:[UIImage imageNamed:#"checkedButton.png"] forState:UIControlStateApplication];
[checkbox setImage:[UIImage imageNamed:#"checkedButton.png"] forState:UIControlStateHighlighted];
[checkbox setImage:[UIImage imageNamed:#"checkedButton.png"] forState:UIControlStateReserved];
[checkbox setImage:[UIImage imageNamed:#"checkedButton.png"] forState:UIControlStateSelected];
}
else
{
//[checkbox setImage:[UIImage imageNamed:#"notSelectedButton.png"] forState:UIControlStateNormal];
}
}
#end
Header
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource>
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
-(UITableViewCell *) GetCellFromTableView: (UITableView *)tableView Sender:(id)sender;
-(void)checkboxSelected:(id)sender;
#end
1) Don't make items an array of strings, make it an array of custom objects that contain both the string you want to display and a BOOL member variable that remembers whether it is selected or not.
2) Only set your image during the cellForRowAtIndexPath method, not in other methods, and do it differently depending on the state of the BOOL variable mentioned above.
3) When the selected state changes due to your action method (or whatever) it should only change the BOOL state variable and then tell the table view to reload its data (which will trigger cellForRowAtIndexPath).
Hi again! I have problem when select single cell. If my single cell a selected - my subview UIButton is highlighted too. What to do?
Thanks all!
This my code:
//
// ThumbnailsBrowser.m
// PHOTO_VIDEO
//
// Created by dev on 07.06.11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#define COUNT 3 // Total number of elements in a single cell.
#define SPINNER_SIZE 20 // Size of spinner in a single cell.
#define THUMBNAIL_SIZE 200 // Size of thumbnail in a single cell.
#define CELL_SIZE 300 // Size of single cell in a table view.
#import "ThumbnailsBrowser.h"
#implementation ThumbnailsBrowser
- (void)sharedDelegate{
[self setDelegate:self];
[self setDataSource:self];
}
- (void)initWithThumbnailsUrl:(NSMutableArray *)url{
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return CELL_SIZE;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Thumbnails";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
for(NSInteger i = 0; i < COUNT; i++){
// Calculate spinner.
float size_one_section = (self.frame.size.width / COUNT);
float size_center_object = size_one_section / 2;
float init_coord_object = size_center_object - (SPINNER_SIZE / 2);
float center_object_y = CELL_SIZE / 2 - (SPINNER_SIZE / 2);
[cell.contentView addSubview:[self activityIndicatorView:CGRectMake(init_coord_object + i * size_one_section, center_object_y, SPINNER_SIZE, SPINNER_SIZE)]];
// Calculate thumbnails.
float init_coord_objectT = size_center_object - (THUMBNAIL_SIZE / 2);
float center_object_yT = CELL_SIZE / 2 - (THUMBNAIL_SIZE / 2);
[cell.contentView addSubview:[self thumbnailsView:CGRectMake(init_coord_objectT + i * size_one_section, center_object_yT, THUMBNAIL_SIZE, THUMBNAIL_SIZE)]];
}
// Set selected cell color.
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor blackColor]];
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
// Create UIActivityIndicatorView and return to cell table view.
- (UIActivityIndicatorView *)activityIndicatorView:(CGRect)frame{
UIActivityIndicatorView * spinner =
[[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
[spinner setFrame:frame];
[spinner startAnimating];
return spinner;
}
// Create thumbnails view.
- (UIButton *)thumbnailsView:(CGRect)frame{
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setFrame:frame];
return myButton;
}
#end
(UIButton *)thumbnailsView:(CGRect)frame{
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setFrame:frame];
[myButton addTarget:self action:#selector(urfunctionName) forControlEvents:UIControlEventTouchUpInside];
return myButton;
}
declare this function in .h
-(void)urfunctionName;
-(void)urfunctionName{
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:NO];
//here call ur buton function
[self urfunctionName];
}
There is a property adjustImageWhenHighlighted which is simply
"A Boolean value that determines whether the image changes when the button is highlighted."
Straight from the library. You can set that to NO for your UIButton in your selectedRow method, and if your action for that button is being accessed, you can set that in there too following #madhu's instructions on setting up the action when it is touched.
Haven't actually tried it, since usually when I have a custom UITableViewCell, I simply subclass it and add all subviews in that subclass.
Also, remember to release allocations.