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.
Related
I've got a fairly simple scenario:
The data structure i am expecting essentially looks like this (the actual layout is way more complicated):
some title
n child text
n child text
n child text
some title
n child text
n child text
n child text
n child text
n child text
some title
n child text
some title
n child text
n child text
n child text
n child text
n child text
In my first attempt i rendered all of it using programmed constraints, which (as you might guess) worked, but performed really bad.
Naturally i went ahead and researched for ways to display dynamic nested content. Unfortunately i was unable to find a good generic way to do this, using cell recycling.
Now i just came up with an idea which seemed very creative, but uber hacky.
What i am going to do, to utilize cell recycling:
I will create a generic cell class to pass TableView.RegisterClassForCellReuse(typeof(MySpecialCell<ItemType, RandomTypeForUniqueness>), "MySpecialCell"+item.Count.ToString());
Setup my cell depending on child count.
My question:
Is there a less cringy way to solve this? (Because this sure feels ugly.)
This is what it should look like in the end:
PS: I really wish RegisterClassForCellReuse would accept factories :(
Follow this steps:
In .h , declare
NSMutableArray *arrayForBool;
NSMutableArray *arrPastOrder;
In .m ,
- (void)viewDidLoad {
arrPastOrder=[[NSMutableArray alloc] init];
int range=1+arc4random()%10;
for(int i=0;i<range;i++)
{
NSMutableArray *arrinside=[[NSMutableArray alloc] init];
int range2=3+arc4random()%5;
for(int j=0;j<range2;j++)
{
if(j==0)
[arrinside addObject:[NSString stringWithFormat:#"Some Header %i",i]];
else
[arrinside addObject:[NSString stringWithFormat:#"Subindex %i",j]];
}
[arrPastOrder addObject:arrinside];
}
arrayForBool=[[NSMutableArray alloc]init];
for (int i=0; i<[arrPastOrder count]; i++)
{
[arrayForBool addObject:[NSNumber numberWithBool:YES]];
}
}
#pragma mark -
#pragma mark TableView DataSource and Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[arrayForBool objectAtIndex:section] boolValue])
{
return [[arrPastOrder objectAtIndex:section] count]-1;
}
else
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *cellid=#"hello";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];
if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
}
BOOL manyCells = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
/********** If the section supposed to be closed *******************/
if(!manyCells)
{
cell.backgroundColor=[UIColor clearColor];
NSLog(#"cellForRowAtIndexPath---if");
cell.textLabel.text=#"";
}
/********** If the section supposed to be Opened *******************/
else
{
//cell.textLabel.text=[NSString stringWithFormat:#"%# %ld",[sectionTitleArray objectAtIndex:indexPath.section],indexPath.row+1];
// ic_keyboard_arrow_up_48pt_2x ic_keyboard_arrow_down_48pt_2x.png
cell.textLabel.text=[NSString stringWithFormat:#"%#",[[arrPastOrder objectAtIndex:indexPath.section] objectAtIndex:indexPath.row+1]];
}
cell.textLabel.textColor=[UIColor blackColor];
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrPastOrder count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%li--%li",(long)indexPath.section, (long)indexPath.row);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[arrayForBool objectAtIndex:indexPath.section] boolValue]) {
return 40;
}
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 100;
}
#pragma mark - Creating View for TableView Section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 540,100)];
sectionView.backgroundColor=[UIColor whiteColor];
sectionView.tag=section;
UILabel *viewLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, 530, 40)];
viewLabel.backgroundColor=[UIColor whiteColor];
viewLabel.textColor=[UIColor blackColor];
viewLabel.font=[UIFont boldSystemFontOfSize:20];
viewLabel.text=[NSString stringWithFormat:#"%#",[[arrPastOrder objectAtIndex:section] objectAtIndex:0]];
[sectionView addSubview:viewLabel];
/********** Add UITapGestureRecognizer to SectionView **************/
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[sectionView addGestureRecognizer:headerTapped];
return sectionView;
}
#pragma mark - Table header gesture tapped
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
//Get which section is open, from here Set the value of arrafool. and expand collapse. Normally whole table is expanded.
}
Just run it. You will get the same structure. happy Coding !!
I just created an assessment in Core Data. My process is to reorder them using button inside tableview.
I took my dynamic button inside tableview but I cant reorder them in tableview cell please help me out. Its like drag and drop.
table=[[UITableView alloc]init];
table.frame=CGRectMake(prev.frame.size.width*1.2, questionlabel.frame.size.height*1.5,self.view.frame.size.width/1.6, self.view.frame.size.height/2);
table.backgroundColor=[UIColor blueColor];
[table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[self.view addSubview:table];
-(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:86.0/255.0 green:161.0/255.0 blue:217.0/255.0 alpha:1.0];
optionButton.sideColor = [UIColor colorWithRed:79.0/255.0 green:127.0/255.0 blue:179.0/255.0 alpha:1.0];
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 addTarget:self
// action:#selector(dynamicclick:)
// forControlEvents:UIControlEventTouchUpInside];
optionButton.tag=bid;
[optionButton setTitle:desc forState:UIControlStateNormal];
optionButton.frame = CGRectMake(5,bid*55,table.frame.size.width-10, 50);
[table addSubview:optionButton];
}
- (void)initTableItem {
self.items = [NSMutableArray array];
[self.items addObject: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"];
}
cell.layoutMargins=UIEdgeInsetsZero;
[cell addSubview:optionButton];
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];
}
I am facing issue regarding Dynamic cell in UITableView. I want to create dynamic rows while user clicked on button in tableview.
E.g.: in mytableview there are two rows as following :
Car :+
Bike :+
When user clicked add button then I have to show two more rows below car cell same thing as while user clicked on in front of bike add button then I have to show two more cells.
I think you need to have 2 sections, a bike and a car section with two data arrays to manage content of all cells. You may need to have two types of cell, an "add" cell and a "standard" cell.
Here is an example:
-In your viewDidiLoad:
self.bikeArray = [NSMutableArray arrayWithArray:#[#"Add bike"]]; // Aray to fill section 0
self.carArray = [NSMutableArray arrayWithArray:#[#"Add car"]]; // Aray to fill section 1
self.typeOfVehicleArray = #[#"Bike", #"Car"];
self.dataArray = #[self.bikeArray, self.carArray];
To create two types of cell, check indexPath.row:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
switch (indexPath.row) {
case 0:{
NSString *addIdentifier = #"addIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:addIdentifier];
if (!cell){
// Add button...
CGFloat buttonWidth = 60.f;
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:addIdentifier];
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(cell.frame.size.width - buttonWidth - 10.f , 5.f, buttonWidth, cell.frame.size.height - 10.f)];
[b setTitle:#"ADD" forState:UIControlStateNormal];
// ...with a wonderful color
b.backgroundColor = [UIColor greenColor];
[b addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:b];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
break;
}
default:{
NSString *standardIdentifier = #"standardIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:standardIdentifier];
if (!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:standardIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
break;
}
}
NSArray *vehicleArray = self.dataArray[indexPath.section];
cell.textLabel.text = [vehicleArray objectAtIndex:indexPath.row];
return cell;
}
Don't forget number of cells / sections:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.dataArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *vehicleArray = self.dataArray[section];
return [vehicleArray count];
}
Then you can implement buttonPressed:
- (void) buttonPressed: (id)sender{
// Find the section
UIButton *b = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)[b superview];
NSInteger section = [self.tableView indexPathForCell:cell].section;
// Get vehicle array (bikeArray or carArray)
NSMutableArray *vehicleArray = self.dataArray[section];
NSString *vehicleType = [self.typeOfVehicleArray objectAtIndex:section];
NSInteger nextVehicle = [vehicleArray count];
NSString *firstRowToAdd = [NSString stringWithFormat:#"%# %lu", vehicleType, (long)nextVehicle];
NSString *secondRowToAdd = [NSString stringWithFormat:#"%# %lu", vehicleType, (long)(nextVehicle + 1)];
// Add object in vehicle array
[vehicleArray addObject:firstRowToAdd];
[vehicleArray addObject:secondRowToAdd];
// Create array of corresponding indexPath and update tableview
NSArray *indexPathArray = #[[NSIndexPath indexPathForRow:nextVehicle inSection:section],
[NSIndexPath indexPathForRow:(nextVehicle + 1) inSection:section]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationRight];
[self.tableView endUpdates];
}
You can control number rows in UITableView's tableView:numberOfRowsInSection: function that is defined in UITableViewDataSource Protocol. Just define an integer variable that holds the number rows user should see. On every Add button click increase the value of variable.
#implementation ViewController {
int numberOfRows;
}
- (void)viewDidLoad {
[super viewDidLoad];
numberOfRows = 3;
}
-(IBAction) addButtonClicked
{
numberOfRows++;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return numberOfRows;
}
I have UITableviewCell and i placed 4 buttons in cell. When i click one button i need to change its background color to red.
Soo right now i have written code for this and when i click one button then that button background color is not changing instead of that same button in some other row changing background color.
Use case:
1.I have 10 rows in UITableView and each cell contains 4 buttons named as
"Good","Better","Best","Worst".
When i click on "Good" button in first row am expecting it should change color to red.
3.Right now if i click "Good " button in first row then its not changing color instead while scrolling down but i can see "Good" button in 4th and 8th is changed to red .
So some mistake in my code for changing color.
Please check my tableview code and Button click code
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int sectionCount;
if(section==0)
{
sectionCount=4;
}else if(section==1){
sectionCount=4;
}else if (section==2){
sectionCount=3;
}else if(section==3){
sectionCount=1;
}
return sectionCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
sharedManager=[Mymanager sharedManager];
static NSString *CellIdentifier = #"cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[questioncell alloc] initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:CellIdentifier];
}
cell.excellentButton.tag=indexPath.row;
cell.goodButotn.tag=indexPath.row;
cell.fineButton.tag=indexPath.row;
cell.dorrButton.tag=indexPath.row;
if(indexPath.section==0){
cell.question.text=[questions objectAtIndex:indexPath.row];
} else if(indexPath.section==1){
cell.question.text=[section1 objectAtIndex:indexPath.row];
}else if(indexPath.section==2){
cell.question.text=[section2 objectAtIndex:indexPath.row];
}else if(indexPath.section==3){
cell.question.text=[section3 objectAtIndex:indexPath.row];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 200;
}
Button click code
- (IBAction)goodButton:(id)sender {
UIButton *button = (UIButton *)sender; // first, cast the sender to UIButton
NSInteger row = button.tag; // recover the row
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
NSString *key=[NSString stringWithFormat:#"%ld",(long)indexPath.row];
[sharedManager.ratingDic setValue:#"Good" forKey:key];
cell.goodButotn.layer.backgroundColor=[[UIColor colorWithRed:39/255.0 green:174/255.0 blue:96/255.0 alpha:100] CGColor ];
cell.betterButton.layer.backgroundColor=[[UIColor clearColor] CGColor ];
cell.bestButton.layer.backgroundColor=[[UIColor clearColor] CGColor ];
cell.worstButton.layer.backgroundColor=[[UIColor clearColor] CGColor ];
}
Please help me to clear this issue
UIButton *button = (UIButton *)sender; <-- this is already your reference to the button. I see there 2 ways to do it
create a custom UITableViewCell and implement methods for resetting all colors and setting the correct color. This is the clean way. Here you can implement more logic and have always the correct corresponding data. Here every of your buttons call an own method and there you have also a clear method.
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if( self = [super initWithStyle:style reuseIdentifier:reuseIdentifier] )
{
[excellentButton addTarget:self action:#selector(clickedExcellentButton) forControlEvents:UIControlEventTouchDown]; // or TouchUp, how ever you like
[goodButton addTarget:self action:#selector(clickedGoodButton) forControlEvents:UIControlEventTouchDown];
[fineButton addTarget:self action:#selector(clickedFineButton) forControlEvents:UIControlEventTouchDown];
[dorrButton addTarget:self action:#selector(clickedWoButton) forControlEvents:UIControlEventTouchDown];
}
return self;
}
-(UIColor *)selectionColor
{
return [UIColor colorWithRed:39/255.0 green:174/255.0 blue:96/255.0 alpha:100];
}
-(void)resetSelection
{
excellentButton.backgroundColor = [UIColor clearColor];
goodButton.backgroundColor = [UIColor clearColor];
fineButton.backgroundColor = [UIColor clearColor];
dorrButton.backgroundColor = [UIColor clearColor];
}
-(void)clickedExcellentButton
{
[self resetSelection];
excellentButton.backgroundColor = [self selectionColor];
NSString *key=[NSString stringWithFormat:#"%ld",(long)indexPath.row];
[sharedManager.ratingDic setValue:#"Excellent" forKey:key]; // if you have your sharedManager object here. If you cannot access it from here, you have to forward it or give the cell a reference to it
}
-(void)clickedGoodButton
{
[self resetSelection];
goodButton.backgroundColor = [self selectionColor];
NSString *key=[NSString stringWithFormat:#"%ld",(long)indexPath.row];
[sharedManager.ratingDic setValue:#"Good" forKey:key];
}
...
or
- (IBAction)goodButton:(id)sender {
UIButton *button = (UIButton *)sender; // this is the button that was clicked
// [...]
for(UIButton *ctrl in [button.superview subviews]) // button.superview get the view that holds him. Subviews all the others in his layer
{
if([ctrl isKindOfClass:[UIButton class]])
{
ctrl.backgroundColor = [UIColor clearColor];
}
}
button.backgroundColor = [UIColor colorWithRed:39/255.0 green:174/255.0 blue:96/255.0 alpha:100];
I create a custom tableview cell, and those four button use the same IBAction when the button been pressed. Then change the background color of that button. It works.
TableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 2;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellID = #"cell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[NSBundle mainBundle] loadNibNamed:#"TableViewCell" owner:self options:nil][0];
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
Button click code
- (IBAction)actionButtonPressed:(UIButton *)sender {
[sender setBackgroundColor:[UIColor redColor]];
}
You don't need to use the layer of the buttons it is enough to set the backgroundColor ( i assume that you are able to access your buttons over cell.Button)
cell.goodButton.backgroundColor = [[UIColor colorWithRed:39/255.0 green:174/255.0 blue:96/255.0 alpha:100] CGColor ];
...
cell.betterButton.backgroundColor = [UIColor clearColor];
cell. bestButton.backgroundColor = [UIColor clearColor];
cell. worstButton.backgroundColor = [UIColor clearColor];
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.