This question already has answers here:
Changing background color of selected cell?
(30 answers)
Closed 8 years ago.
I am making an app in which I am showing my data in a UITableView. I am stuck. I want to change the colour of the selected cell. How to do this?
Below is my code in -didSelectRowAtIndexPath
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"the messageid==%#",[[self.inboxmessagesarray objectAtIndex:indexPath.row ] objectForKey:#"messageId"]);
manage.messageid=[[self.inboxmessagesarray objectAtIndex:indexPath.row ] objectForKey:#"messageId"]; // here i pass the value to singleton class
[self performSegueWithIdentifier:#"segueIdentifier" sender:tableView];
}
Update your code as mentioned below:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"the messageid==%#",[[self.inboxmessagesarray objectAtIndex:indexPath.row ] objectForKey:#"messageId"]);
manage.messageid = [[self.inboxmessagesarray objectAtIndex:indexPath.row ] objectForKey:#"messageId"]; // here i pass the value to singleton class
[self performSegueWithIdentifier:#"segueIdentifier" sender:tableView];
// Add this line to set selected default gray style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
}
Use selectionStyle property to get cell highlighed. For more details refer UITableViewCellSelectionStyle
May be this will be useful to u...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIView *selectedRowColor = [[UIView alloc] init];
selectedRowColor.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = selectedRowColor;
}
in your cellForRowAtIndexPath has two options for selection only Blue and another one is Gray
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath
{
/// here your cell identifier name and details
UIView *changeselectionColor = [[UIView alloc] init];
changeselectionColor.backgroundColor = [UIColor colorWithRed:(245.0/255.0) green:(245.0/255.0) blue:(245.0/255.0) alpha:1]; // change the RGB as you like
cell.selectedBackgroundView = changeselectionColor;
//...... here add your cell details.. //
}
or in another choice no 2 call this method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIView * changeselectionColor = [[UIView alloc] init];
changeselectionColor.backgroundColor = [UIColor GreenColor];
cell.selectedBackgroundView = changeselectionColor;
}
Related
Following is my cellForRowAtIndexPath method in MyOrdersController.m file...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:#""];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
self.shipmentReferenceNumberTextLabel = [[UILabel alloc]init];
self.shipmentReferenceNumberTextLabel.text = amountArray[indexPath.row];
self.shipmentReferenceNumberTextLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:10];
tableView.tableFooterView = [UIView new];
cell.layer.borderWidth = 1.0;
cell.layer.cornerRadius = 10;
cell.layer.borderColor = [UIColor blackColor].CGColor;
[cell.contentView addSubview:self.productAmountLabel];
[cell.contentView addSubview:self.productAmountTextLabel];
return cell;
}
I have got a textlabel shipmentReferenceNumberTextLabel in it. I have to grab the value of shipmentReferenceNumber when a user clicks on a particular cell and I have to make json request with it in a file called APIRequest.m. Im trying grab its value as follows,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
tabBar = [self.storyboard instantiateViewControllerWithIdentifier:#"TabBarController"];
[self.navigationController pushViewController:tabBar animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
MyOrdersController *detailVC = [[MyOrdersController alloc]init];
NSLog(#"%#", detailVC.shipmentReferenceNumberTextLabel.text);
}
The problem is that, its printing null while im trying to grab its value. How can I sort out this issue.
You can get value of Lable from an array.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSLog(#"%#",amountArray[indexPath.row]);
}
You will get selected row's label value.
I have a question about UITAbleViewCell's.
I have implemented UITableViewDelegate method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
cell.textLabel.textColor = [UIColor redColor];
cell.textLabel.text = #"Title";
}
After I click on desired cell, nothing happens...
Why it doesn't work as I expected? Also, what should I do to make it work?
You have to create some base model for cell states e.g:
#property NSString *modelState = #"red"; // this is fast hint, but it can be a enum with states.
all cell will have one title after tap.
... other controller code...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.restaurantTable dequeueReusableCellWithIdentifier:#"cell_ID"];
// cell customization method
[self customizeCell:cell accordingToStateStr:modelState];
return cell;
}
... other controller code...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
// Set other state for cell
self.modelState = #"red";
[tableView reloadData];
}
- (void)customizeCell:(UITableViewCell*)cell accordingToStateStr:(NSString *)str {
if ([str isEqualToString:#"red"]) {
cell.backgroundColor = [UIColor redColor];
cell.textLabel.textColor = [UIColor redColor];
cell.textLabel.text = #"Title";
} else if(...) {
//Other options..
}
}
[tableView reloadData]; - will trigger once again "cellForRow" method and your table will be redrawn according to new model.
You can use for cell states emuns instead NSString object (this is only scaffold for you).
Try this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// config the selected cell
....
}
You should ask the UITableView for the cell directly rather than ask its delegate (self in your code). Cause its delegate may dequeue or create a fresh cell rather than giving you the cell seleceted.
Hi I am developing small IOS application in which I am loading some data inside tableview. So what I want to do I want to make first row as default selected row with some selected background color. So I tried following things
// inside viewDidLoad make first row as selected row
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
[_tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:0];
// inside cellForRowAtIndexPath set some selection color
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [customColor colorWithHexString:#"91979755"];
[cell setSelectedBackgroundView:bgColorView];
}
But it is not working. Any one know how to do this? Need some help. Thank you.
Try this code,put this in cellForRow method:
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor cyanColor];
[cell setSelectedBackgroundView:bgColorView];
And for specific row put this in if condition.
Hope it works.
self.indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[_tabelView selectRowAtIndexPath:self.indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
// inside cellForRowAtIndexPath set some selection color
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.indexPath.row==indexPath.row){
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [customColor colorWithHexString:#"91979755"];
[cell setSelectedBackgroundView:bgColorView];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.indexPath=indexPath;
}
I have UITableView in which i want to add Background image on first cell in viewDidLoad method, after adding image on first cell, when user selects any other row i want to hide my background image.
Is it possible to do ?
Please help and thanks in advance.
Edit:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath{
if(indexPath.row==0){
cell.backgroundView = [ [UIImageView alloc] initWithImage:[[UIImage imageNamed:#"active-tab.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
flag=true;
NSLog(#"willDisplayCell");
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (flag==true) {
cell.backgroundView = nil; //How to get `cell` here ?
//How to remove BGImage from first cell ???
}
}
Take a look at this question and the second answer gives a great description.
In short you should not be using the viewDiLoad callback but instead the
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ... }
From here you can customise each cell's background as you wish, just reload the row when the user clicks.
How to customize the background color of a UITableViewCell?
EDIT
Now because you added your code I can clearly see the problem:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"BTSTicketsCellIdentifier";
CRHomeCategCell *cell = (CRHomeCategCell *)[_tblCateg dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundView = nil;
}
This does not do what you think it does. dequeueReusableCellWithIdentifier:CellIdentifier gives you a NEW instance of a cell based off the one identified by the identifier.
You are not getting a reference to the row here, you are creating a new row and settings its background to nil.
Your code should be something more like this:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath{
if(indexPath.row==0){
if(cell.backgroundView == nil)
{
cell.backgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"active-tab.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
NSLog(#"willDisplayCell");
}
else
{
cell.backgroundView = nil;
NSLog(#"willHideCell");
}
}
}
This is not a great solution, I personally would do something more like having this custom cell hold a boolean and switch its state and check that. But this is up to you to develop, this is the general idea of how it should work.
EDIT 2:
Since you are determined to run it inside didSelectRowAtIndexPath and also completely incapable of doing any level of research or putting any effort into your work might I suggest the method:
tableView cellForRowAtIndexPath:<#(NSIndexPath *)#>
it works add table view delegates in your class
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath
*)indexPath
{
if((indexPath.row)==0) {
cell.backgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"normal.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
yourcustomcell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"pressed.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
or
cell.backgroundView = nil;
[tableview reloadData];
}
For some reason my UITableView Delegate method didSelectRowAtIndexPath is not getting called until after I select the row. Also, although I set the editing style of my UITableView to UITableViewCellEditingStyleDelete, when I swipe my finger across the tableview it doesn't show the delete button. I have set the delegate and datasource properties of my tableview in storyboard to my viewcontroller, but the delegate methods still aren't getting called properly. The cells still function and will navigate to my other detailview, but I'm just getting some very weird behavior. Here's the code I'm using for my tableview:
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_lists count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"MasterListCell";
/* Set up list cell */
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 15.0f, 15.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:#"cell-arrow.png"]];
cell.accessoryView = myImage; //cellArrowNotScaled;
cell.editingAccessoryType = UITableViewCellEditingStyleDelete;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
/* Define a new List */
List *list = [_lists objectAtIndex:indexPath.row];
// cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont fontWithName:#"Roboto-Medium" size:15];
cell.textLabel.text = list.name;
cell.textLabel.highlightedTextColor = [UIColor blackColor];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:
(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Are you sure?" message:#"This list will be permanently deleted." delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK",nil];
[alert show];
}
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *currentSelectedIndexPath = [tableView indexPathForSelectedRow];
if (currentSelectedIndexPath != nil)
{
[[tableView cellForRowAtIndexPath:currentSelectedIndexPath] setBackgroundColor:[UIColor yellowColor]];
}
return indexPath;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"did select row");
[[tableView cellForRowAtIndexPath:indexPath] setBackgroundColor:[UIColor yellowColor]];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (cell.isSelected == YES)
{
[cell setBackgroundColor:[UIColor yellowColor]];
}
else
{
[cell setBackgroundColor:[UIColor whiteColor]];
}
}
Update answer
From your comment below, I see what you're getting at. You're trying to fake a custom selected background for grouped style (which can't be customized without providing custom images) by turing of selection highlighting and instead setting the unselected background color when the cell is tapped. You can do this in shouldHighlightRowAtIndexPath:
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor greenColor];
return YES;
}
This method gets called before didSelectRowAtIndexPath even when selection style is none. You'll need to elaborate on the above solution to set the color back when the cell is supposed to be unhighlighted.
Original answer
didSelectRowAtIndexPath is not getting called until after I select the row
That is by design, hence the past tense "did" in the name.
Also, although I set the editing style of my UITableView to UITableViewCellEditingStyleDelete, when I swipe my finger across the tableview it doesn't show the delete button.
You've got to implement the data source method tableView:commitEditingStyle:forRowAtIndexPath: to have the delete button appear. If you think about it it makes sense. You haven't provided a way for your data source to respond to the edit, so iOS concludes that it shouldn't edit.
I'm saying that when I press down on a cell with UITableViewSelectionStyleBlue it shows up blue. However, when I set it to none and attempt to change the background color in didSelectRowAtIndexPath it doesn't change until after I have lifted my finger up off the cell. I want the background color of the cell to change when I put my finger down without lifting it
What are you ultimately trying to accomplish? It sounds like you want to do a custom highlight color. The way to do that is to replace the cell's selectedBackgroundView with your own view and set that view's background color:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//...
cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.bounds];
cell.selectedBackgroundView.backgroundColor = [UIColor greenColor];
//...
}
If that's not what you're going for, please clarify and I'll update my answer.