Monotouch.Dialog StyledStringElement full image [duplicate] - iphone

I have created a custom UITableViewCell. The table view is showing data fine. What I am stuck in is when user touches cell of tableview, then I want to show the background color of the cell other than the default [blue color] values for highlighting the selection of cell.
I use this code but nothing happens:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];

No need for custom cells. If you only want to change the selected color of the cell, you can do this:
Objective-C:
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
Swift:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView

I think you were on the right track, but according to the class definition for selectedBackgroundView:
The default is nil for cells in plain-style tables (UITableViewStylePlain) and non-nil for section-group tables UITableViewStyleGrouped).
Therefore, if you're using a plain-style table, then you'll need to alloc-init a new UIView having your desired background colour and then assign it to selectedBackgroundView.
Alternatively, if all you wanted was a gray background when the cell is selected, you could use this:
cell.selectionStyle = UITableViewCellSelectionStyleGray;

Table View Cell selection background color can be set via the Storyboard in Interface Builder:

If you have a grouped table with just one cell per section, just add this extra line to the code:
bgColorView.layer.cornerRadius = 10;
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release];
Don't forget to import QuartzCore.

Swift 3: for me it worked when you put it in the cellForRowAtIndexPath: method
let view = UIView()
view.backgroundColor = UIColor.red
cell.selectedBackgroundView = view

The following works for me in iOS 8.
I have to set the selection style to UITableViewCellSelectionStyleDefault for custom background color to work. If any other style, the custom background color will be ignored. There seems to be a change in behaviours as previous answers needs to set style to none instead.
The full code for the cell as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// This is how you change the background color
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
return cell;
}

Create a custom cell for your table cell and in the custom cell class.m put the code below, it will work fine. You need to place the desired color image in selectionBackground UIImage.
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
UIImage *selectionBackground = [UIImage imageNamed:#"yellow_bar.png"];
UIImageView *iview=[[UIImageView alloc] initWithImage:selectionBackground];
self.selectedBackgroundView=iview;
}

Swift 3.0 extension
extension UITableViewCell {
var selectionColor: UIColor {
set {
let view = UIView()
view.backgroundColor = newValue
self.selectedBackgroundView = view
}
get {
return self.selectedBackgroundView?.backgroundColor ?? UIColor.clear
}
}
}
cell.selectionColor = UIColor.FormaCar.blue

In Swift 4, you can also set the background color of your table cell globally (taken from here):
let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *view = [[UIView alloc] init];
[view setBackgroundColor:[UIColor redColor]];
[cell setSelectedBackgroundView:view];
}
We need to set the selected background view in this method.

Swift 4+:
Add following lines in your table cell
let bgColorView = UIView()
bgColorView.backgroundColor = .red
self.selectedBackgroundView = bgColorView
Finally it should be as below
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
let bgColorView = UIView()
bgColorView.backgroundColor = .red
self.selectedBackgroundView = bgColorView
}

If you want to add a custom highlighted color to your cell (and your cell contains buttons,labels, images,etc..) I followed the next steps:
For example if you want a selected yellow color:
1) Create a view that fits all the cell with 20% opacity (with yellow color) called for example backgroundselectedView
2) In the cell controller write this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundselectedView.alpha=1;
[super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundselectedView.alpha=0;
[super touchesEnded:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundSelectedImage.alpha=0;
[super touchesCancelled:touches withEvent:event];
}

If you are using a custom TableViewCell, you can also override awakeFromNib:
override func awakeFromNib() {
super.awakeFromNib()
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}

I want to note that the XIB editor offers you the following standard options:
Section: blue/gray/none
(the right-hand column with options, 4th tab, first group "Table View Cell", 4th subgroup, the 1st of 3 items reads "Selection")
Probably what you want to do may be achieved by selecting the right standard option.

One more tip to Christian's way to show rounded corner background for grouped table.
If I use cornerRadius = 10 for cell, it shows four corner's rounded selection background. It's not the same with table view's default UI.
So, I think about easy way to resolve it with cornerRadius.
As you can see from the below codes, check about cell's location (top, bottom, middle or topbottom) and add one more sub layers to hide top corner or bottom corner. This just shows exactly same look with default table view's selection background.
I tested this code with iPad splitterview. You can change patchLayer's frame position as you needed.
Please let me know if there is more easier way to achieve same result.
if (tableView.style == UITableViewStyleGrouped)
{
if (indexPath.row == 0)
{
cellPosition = CellGroupPositionAtTop;
}
else
{
cellPosition = CellGroupPositionAtMiddle;
}
NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
if (indexPath.row == numberOfRows - 1)
{
if (cellPosition == CellGroupPositionAtTop)
{
cellPosition = CellGroupPositionAtTopAndBottom;
}
else
{
cellPosition = CellGroupPositionAtBottom;
}
}
if (cellPosition != CellGroupPositionAtMiddle)
{
bgColorView.layer.cornerRadius = 10;
CALayer *patchLayer;
if (cellPosition == CellGroupPositionAtTop)
{
patchLayer = [CALayer layer];
patchLayer.frame = CGRectMake(0, 10, 302, 35);
patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
[bgColorView.layer addSublayer:patchLayer];
}
else if (cellPosition == CellGroupPositionAtBottom)
{
patchLayer = [CALayer layer];
patchLayer.frame = CGRectMake(0, 0, 302, 35);
patchLayer.backgroundColor = YOUR_BACKGROUND_COLOR;
[bgColorView.layer addSublayer:patchLayer];
}
}
}

As per custom color for a selected cell in UITableView, great solution as per Maciej Swic's answer
Just to add to that, you declare Swic's answer in the Cell configuration usually under:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
And for an added effect, instead of the system colors, you may use RGB values for a custom color look. In my code this is how I achieved it:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
}
static NSString *CellIdentifier = #"YourCustomCellName";
MakanTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if (cell == nil) {
cell = [[[NSBundle mainBundle]loadNibNamed:#"YourCustomCellClassName" owner:self options:nil]objectAtIndex:0];
}
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:255.0/256.0 green:239.0/256.0 blue:49.0/256.0 alpha:1];
bgColorView.layer.cornerRadius = 7;
bgColorView.layer.masksToBounds = YES;
[cell setSelectedBackgroundView:bgColorView];
return cell;
}
Let me know if that works for you as well. You can mess with the cornerRadius number for the effects on the corners of the selected cell.

To add the background for all cells (using Maciej's answer):
for (int section = 0; section < [self.tableView numberOfSections]; section++) {
for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];
//stuff to do with each cell
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
}
}

I've got a slightly different approach than everyone else that reflects the selection on touch rather than after being selected. I have a subclassed UITableViewCell. All you have to do is set the background color in the touch events, which simulates selection on touch, and then set the background color in the setSelected function. Setting the background color in the selSelected function allows for deselecting the cell. Make sure to pass the touch event to the super, otherwise the cell won't actually act as if its selected.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.backgroundColor = UIColor(white: 0.0, alpha: 0.1)
super.touchesBegan(touches, withEvent: event)
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
self.backgroundColor = UIColor.clearColor()
super.touchesCancelled(touches, withEvent: event)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
self.backgroundColor = selected ? UIColor(white: 0.0, alpha: 0.1) : UIColor.clearColor()
}

To override UITableViewCell's setSelected also works.
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}

for those that just want to get rid of the default selected grey background put this line of code in your cellForRowAtIndexPath func:
yourCell.selectionStyle = .None

for Swift 3.0:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.contentView.backgroundColor = UIColor.red
}

I use below approach and works fine for me,
class MyTableViewCell : UITableViewCell {
var defaultStateColor:UIColor?
var hitStateColor:UIColor?
override func awakeFromNib(){
super.awakeFromNib()
self.selectionStyle = .None
}
// if you are overriding init you should set selectionStyle = .None
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let hitColor = hitStateColor {
self.contentView.backgroundColor = hitColor
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let defaultColor = defaultStateColor {
self.contentView.backgroundColor = defaultColor
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if let defaultColor = defaultStateColor {
self.contentView.backgroundColor = defaultColor
}
}
}

1- Add a view to the content view of your cell.
2- Right click your cell.
3- Make the added view as "selectedBackgroundView".

Here is the important parts of the code needed for a grouped table. When any of the cells in a section are selected the first row changes color. Without initially setting the cellselectionstyle to none there is an annonying double reload when the user clicks row0 where the cell changes to bgColorView then fades and reloads bgColorView again. Good Luck and let me know if there is a simpler way to do this.
- (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];
}
if ([indexPath row] == 0)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView *bgColorView = [[UIView alloc] init];
bgColorView.layer.cornerRadius = 7;
bgColorView.layer.masksToBounds = YES;
[bgColorView setBackgroundColor:[UIColor colorWithRed:.85 green:0 blue:0 alpha:1]];
[cell setSelectedBackgroundView:bgColorView];
UIColor *backColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:1];
cell.backgroundColor = backColor;
UIColor *foreColor = [UIColor colorWithWhite:1 alpha:1];
cell.textLabel.textColor = foreColor;
cell.textLabel.text = #"row0";
}
else if ([indexPath row] == 1)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
cell.backgroundColor = backColor;
UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
cell.textLabel.textColor = foreColor;
cell.textLabel.text = #"row1";
}
else if ([indexPath row] == 2)
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIColor *backColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
cell.backgroundColor = backColor;
UIColor *foreColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
cell.textLabel.textColor = foreColor;
cell.textLabel.text = #"row2";
}
return cell;
}
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:[indexPath section]];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
[tableView selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionNone];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tvStat cellForRowAtIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
#pragma mark Table view Gestures
-(IBAction)singleTapFrom:(UIGestureRecognizer *)tapRecog
{
CGPoint tapLoc = [tapRecog locationInView:tvStat];
NSIndexPath *tapPath = [tvStat indexPathForRowAtPoint:tapLoc];
NSIndexPath *seleRow = [tvStat indexPathForSelectedRow];
if([seleRow section] != [tapPath section])
[self tableView:tvStat didDeselectRowAtIndexPath:seleRow];
else if (seleRow == nil )
{}
else if([seleRow section] == [tapPath section] || [seleRow length] != 0)
return;
if(!tapPath)
[self.view endEditing:YES];
[self tableView:tvStat didSelectRowAtIndexPath:tapPath];
}

[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
Make sure you have used the above line to use the selection effect

override func setSelected(selected: Bool, animated: Bool) {
// Configure the view for the selected state
super.setSelected(selected, animated: animated)
let selView = UIView()
selView.backgroundColor = UIColor( red: 5/255, green: 159/255, blue:223/255, alpha: 1.0 )
self.selectedBackgroundView = selView
}

In case of custom cell class. Just override:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
if (selected) {
[self setBackgroundColor: CELL_SELECTED_BG_COLOR];
[self.contentView setBackgroundColor: CELL_SELECTED_BG_COLOR];
}else{
[self setBackgroundColor: [UIColor clearColor]];
[self.contentView setBackgroundColor: [UIColor clearColor]];
}
}

It's easy when the table view style is plain, but in group style, it's a little trouble, I solve it by:
CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kGroupTableViewCellWidth+2, cellHeight)];
view.backgroundColor = kCommonHighlightedColor;
cell.selectedBackgroundView = view;
[view release];
UIRectCorner cornerFlag = 0;
CGSize radii = CGSizeMake(0, 0);
NSInteger theLastRow = --> (yourDataSourceArray.count - 1);
if (indexPath.row == 0) {
cornerFlag = UIRectCornerTopLeft | UIRectCornerTopRight;
radii = CGSizeMake(10, 10);
} else if (indexPath.row == theLastRow) {
cornerFlag = UIRectCornerBottomLeft | UIRectCornerBottomRight;
radii = CGSizeMake(10, 10);
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:cornerFlag cornerRadii:radii];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = maskPath.CGPath;
view.layer.mask = shapeLayer;
noted the kGroupTableViewCellWidth, I define it as 300, it's the width of group table view cell width in iPhone

I'm using iOS 9.3 and setting the color through the Storyboard or setting cell.selectionStyle didn't work for me, but the code below worked:
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:55 / 255.0
green:141 / 255.0
blue:211 / 255.0
alpha:1.0];
cell.selectedBackgroundView = customColorView;
return cell;
I found this solution here.

Try Following code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdArray objectAtIndex:indexPath.row] forIndexPath:indexPath];
// Configure the cell...
cell.backgroundView =
[[UIImageView alloc] init] ;
cell.selectedBackgroundView =[[UIImageView alloc] init];
UIImage *rowBackground;
UIImage *selectionBackground;
rowBackground = [UIImage imageNamed:#"cellBackgroundDarkGrey.png"];
selectionBackground = [UIImage imageNamed:#"selectedMenu.png"];
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
return cell;
}
//Swift Version:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
cell.selectedBackgroundView = UIImageView()
cell.backgroundView=UIImageView()
let selectedBackground : UIImageView = cell.selectedBackgroundView as! UIImageView
selectedBackground.image = UIImage.init(named:"selected.png");
let backGround : UIImageView = cell.backgroundView as! UIImageView
backGround.image = UIImage.init(named:"defaultimage.png");
return cell
}

Related

can't click UIButton inside a cell in UITableview

searched already some possible fixes but all did not solve mine.
i keep clicking the cell in the uitableview rather than the buttons inside it.
here is my code:
- (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];
}
cell.backgroundColor = [UIColor blackColor];
UIView *v = nil;
NSArray *array = [cell subviews];
for (v in array) {
NSLog(#"%#",[v class]);
if( [v isKindOfClass:[UIView class]] ){
[v removeFromSuperview];
}
}
//tb
if (tableView == self.tb) {
v = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.tb.bounds.size.width, 120.0)];
if([feeds count]>0){
UIImageView *box=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"statusBox.png"]];
box.userInteractionEnabled = YES;
[v addSubview:box];
AsyncImageView *imageView1 = [[AsyncImageView alloc] initWithFrame:CGRectMake(10, 20.0f, 34.0f, 34.0f)];
imageView1.contentMode = UIViewContentModeScaleAspectFill;
imageView1.clipsToBounds = YES;
//cancel loading previous image for cell
[[AsyncImageLoader sharedLoader] cancelLoadingImagesForTarget:imageView1];
if (users1 != nil && users1.imagelink != nil && (id) users1.imagelink != [NSNull null]){
imageView1.imageURL = [NSURL URLWithString:users1.imagelink];
}
else{
imageView1.image=[UIImage imageNamed:#"default_ProfilePic.png"];
}
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(myFunction:)];
tapped.numberOfTapsRequired = 1;
[imageView1 addGestureRecognizer:tapped];
[tapped release];
imageView1.userInteractionEnabled = NO;
[v addSubview:imageView1];
UIFont *font = [UIFont fontWithName:#"TrebuchetMS-Bold" size:11];
UILabel *descLabel1 = [[UILabel alloc] initWithFrame: CGRectMake(52, 23, 160, 48)];
descLabel1.text = [NSString stringWithFormat:#"%# %#",users1.userfirstn,users1.userlastn];
descLabel1.textColor = [UIColor blackColor];
descLabel1.font = font;
descLabel1.adjustsFontSizeToFitWidth=YES;
descLabel1.numberOfLines = 0;
CGSize expectedLabelSize = [descLabel1.text sizeWithFont:descLabel1.font
constrainedToSize:descLabel1.frame.size
lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = descLabel1.frame;
newFrame.size.height = expectedLabelSize.height;
descLabel1.frame = newFrame;
descLabel1.numberOfLines = 0;
descLabel1.userInteractionEnabled = NO;
[v addSubview:descLabel1];
UILabel *descLabel2= [[UILabel alloc] initWithFrame: CGRectMake(52, 43, 200, 48)];
StatusClass *stat1=[feeds objectAtIndex:indexPath.row];
descLabel2.text = [stat1 statcreate];
descLabel2.textColor = [UIColor blackColor];
descLabel2.font = font;
descLabel2.adjustsFontSizeToFitWidth=YES;
descLabel2.numberOfLines = 0;
CGSize expectedLabelSize2 = [descLabel2.text sizeWithFont:descLabel2.font
constrainedToSize:descLabel2.frame.size
lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame2 = descLabel2.frame;
newFrame2.size.height = expectedLabelSize2.height;
descLabel2.frame = newFrame2;
descLabel2.numberOfLines = 0;
descLabel2.userInteractionEnabled = NO;
[v addSubview:descLabel2];
UILabel *descLabel3= [[UILabel alloc] initWithFrame: CGRectMake(10, 63, 280, 80)];
StatusClass *stat=[feeds objectAtIndex:indexPath.row];
descLabel3.text = [stat stattext];
descLabel3.textColor = [UIColor blackColor];
descLabel3.font = font;
descLabel3.adjustsFontSizeToFitWidth=YES;
descLabel3.numberOfLines = 0;
descLabel3.userInteractionEnabled = NO;
[v addSubview:descLabel3];
//comment button
UIButton *buttonC = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonC addTarget:self action:#selector(sendComment:) forControlEvents:UIControlEventTouchUpInside];
[buttonC setImage:[UIImage imageNamed:#"comment.png"] forState:UIControlStateNormal];
buttonC.frame = CGRectMake(2, 160, 145, 35);
buttonC.userInteractionEnabled = YES;
[v addSubview:buttonC];
//share button
UIButton *buttonS = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonS.tag = indexPath.row;
[buttonS addTarget:self action:#selector(sendShare:) forControlEvents:UIControlEventTouchUpInside];
[buttonS setImage:[UIImage imageNamed:#"share.png"] forState:UIControlStateNormal];
buttonS.frame = CGRectMake(150, 160, 140, 35);
buttonS.userInteractionEnabled = YES;
[v addSubview:buttonS];
}
v.userInteractionEnabled = YES;
[cell addSubview:v];
}
return cell;
}
I also tried the UITapGestureRecognizer for the buttons and still not working.
Thanks.
I'm just baffled by this issue....
I managed to fix this problem by doing this on one project:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("RegCell", forIndexPath: indexPath) as! CustomCell
cell.contentView.userInteractionEnabled = false // <<-- the solution
return cell
}
but the same did not work for a different project. I have no idea why...
There is another potential cause of problems like this one, and that is UITableViewCells now have a contentView. This can and will be placed in front of other views in your custom table view cells in order to pick up touches and detect cell selection. In doing so, it may block touches to any views behind it. I've especially noticed this annoyance when creating cells using nibs.
The accepted means for dealing with this is to ensure that all subviews are added not to the tableview cell itself, but to its contentView. This is a read-only property that adjusts its own frame under certain circumstances, for example when slid sideways to reveal the delete button, or during editing mode. You should therefore ensure that any items you do add to the contentVieware intelligently sized and have the correct resizing behaviour.
Also be aware that by adding cells to the contentView, you may yourself block touches to it and thus prevent the cell from being selected. I personally try not to allow cell selection in tableviews containing cells with custom user-enabled controls. It only leads to confusion and awkward interfaces. In fact, I'm seriously considering replacing all UITableViews in my future projects with UICollectionViews, which are far more adaptable.
-Ash
I was doing this:
let plusButton: UIButton = {
let v = UIButton()
v.setImage(plusImg, for: .normal)
v.tintColor = .dark
v.translatesAutoresizingMaskIntoConstraints = false
// adding targets here did not work
v.addTarget(self, action: #selector(plusButtonHandler), for: .touchUpInside)
return v
}()
And it appears invoking the addTarget method inside of the closure did not work.
When I factored the addTarget method out and instead put it in the initializer, everything worked!
In my case I tried to added the UIButton direct to the cell by self.addSubview(myButton), so I changed to self.contentView.addSubview(myButton) and it worked
It seems the contentView was in front of the myButton so the button won't receive the tap gesture.
Your UIButton='s y offset is given as 160 and UIView's height is just given as 120. Please change the UIButton's y offset and try.
The UITableViewCell is handling all the gestures by default.
Set cell.selectionStyle = UITableViewCellSelectionStyleNone; to make it disable the default behaviour.
For Swift 3 and Storyboard
For me, I had to enable multiple touch inside the content view, and enable user interaction on everything - the table view, table view cell, content view, and UIButton. I was using storyboard.
I also set up my tableview cell as a subclass.
Since I couldn't find an answer here when I was exploring the problem, I posted another question on stack overflow about this. You can see my code and download a project with this working here: Can't click button inside UITableViewCell?
I ran into this problem, but in my case it was not related to the table view, instead it was because I was using subviews in my button for which userInteractionEnabled was true, setting that value for false (NO) for all the button's subviews fixed the issue for me.
I have the same issue, and somehow I figured out my mistake.
After I changed the constraints with self(UITableViewCell) to constraints with contentView of self(UITableViewCell),my cell's button is clickable again.
Update swift 4.2
in func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
add it : cell.buttonCheckBox.isUserInteractionEnabled = false
OR, uncheck User Interaction Enabled inspector
Now you can select the button as well as a cell.
This works for me :)
Create a custom UITableViewCell. Refer this link.
Say you have a UIButton by the name of displayButton, you can do something like this:
Inside your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath, after you create your cell,
[cell.dislayButton addTarget: self
action: #selector(replyButtonPressed:withEvent:)
forControlEvents: UIControlEventTouchUpInside];
And the create the method like so in your ViewController:
- (void) replyButtonPressed: (id) sender withEvent: (UIEvent *) event
{
UITouch * touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView: self.tableView];
NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location];
}
try this
public override void SetSelected(bool selected, bool animated)
{
// this.interestsButton.Selected = true;
if (selected)
{
// this.TextLabel.TextColor = UIColor.Red;
//this.interestsButton.ShowsTouchWhenHighlighted = true;
this.interestsButton.BackgroundColor = UIColor.Purple;
//this.interestsButton.SetTitleColor(UIColor.Red, UIControlState.Highlighted);
}
else
{
}
// cell.ContentView.UserInteractionEnabled = false;
base.SetSelected(selected, animated);
}
Tested on "Mvvmcross.iOS" only
Just to add to the discussion:
FOR SWIFT 5+
Is important to set the variable as lazy var when invoking the addTarget method inside of the closure. See:
lazy var plusButton: UIButton = {
let v = UIButton()
v.setImage(plusImg, for: .normal)
v.tintColor = .dark
v.translatesAutoresizingMaskIntoConstraints = false
v.addTarget(self, action: #selector(plusButtonHandler), for: .touchUpInside)
return v
}()
Now, about the contentView of the tableViewCells that appears above the cell stoping the click at the cell: I used the code above and also set the contentView to .ishidden = true and it worked!
Probably there is something linked to the lifecycle of the methods.
Hope it helps too.
If you have no alternative selector for the UIButton pressed inside some UITableViewCell you need turn off userInteractionEnabled for the button
cellButton.userInteractionEnabled = false
In this case any button touch will propagate to the cell touch.

UIProgressview in subclassed UITableViewCell need to be used in other UIViewController

I have a subclassed custom UITableViewCell, in which I am inserting a progress view in it.
here is how:
-(void)layoutSubviews {
applicationDelegate = [[UIApplication sharedApplication] delegate];
[super layoutSubviews];
self.imageView.frame = CGRectMake(0, 0, self.frame.size.height, self.frame.size.height);
self.textLabel.frame = CGRectMake( self.imageView.frame.size.width + 20, self.textLabel.frame.origin.y, self.textLabel.frame.size.width, self.textLabel.frame.size.height);
progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
progressView.frame = CGRectMake(self.textLabel.frame.origin.x, 50, 150, 100);
progressView.progress = 0.0f;
progressView.trackTintColor = [UIColor clearColor];
progressView.progressTintColor = [UIColor redColor];
progressView.tag = 101;
[progressView setHidden:YES];
[self.contentView addSubview:progressView];
}
Now when in other view controller I want to show this elements only in first cell, so I am trying to hide these elements in other cells. Here is how I am trying to do this in cellForRowAtIndexPath: method:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * cellIdentifier = #"cellId";
CustomCell * cell = [self.tableview dequeueReusableHeaderFooterViewWithIdentifier:cellIdentifier];
if (cell == Nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
if (indexPath.row == 0) {
imageData = UIImageJPEGRepresentation(cell.imageView.image, 100);
filename = cell.textLabel.text;
[(UIProgressView*)[cell.contentView viewWithTag:101] setHidden:NO];<==Not Working
}
return cell;
}
How to use this UIElements in custom UITableView subclass in my ViewController ?
I have not used xib file, everything is done programmatically. I have beed playing around this for whole day now, any one with any idea here ?
If only the 1st row needs to show the progress view, why not only use the custom cell for row 0 and then use a standard UITableViewCell for rows >1?
I would also recommend adding progressView to self.contentView in an init method and not in layoutSubviews. layoutSubviews is intended to position the views you already have (not add new ones) because it can be called many times over the lifetime of the cell.
I would add a BOOL property to the custom cell that determines if you should show the progress indicator (and removes it when set to NO). In cellForRowAtIndexPath: you could set it appropriately for the given row.
In CustomCell.h:
#property(nonatomic, assign) BOOL shouldShowProgressView;
In CustomCell.m:
- (void)setShouldShowProgressView:shouldShowProgressView {
_shouldShowProgressView = shouldShowProgressView;
if (shouldShowProgressView) {
if (self.someProgressView == nil) {
// add your progress view from scratch
}
[self.contentView addSubview:self.someProgressView];
} else {
[self.someProgressView removeFromSuperview];
}
}
In your table controller:
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
static NSString *cellIdentifier = #"cellId";
CustomCell *cell = [self.tableview dequeueReusableHeaderFooterViewWithIdentifier:cellIdentifier];
if (cell == Nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
if (indexPath.row == 0) {
cell.shouldShowProgressView = YES;
} else {
cell.shouldShowProgressView = NO;
}
return cell;
}

can't change UITableViewCell background color

I have UITableViewCell that fits on UITableView, but somehow I can't change the background color when entering editing style mode.. I've tried everything on the web, search all day long, but still couldn't get it fixed (I've searched StackOverflow as-well). please, help me.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray* views = [[NSBundle mainBundle] loadNibNamed:#"MainTableViewCell" owner:nil options:nil];
for (UIView *view in views) {
if([view isKindOfClass:[UITableViewCell class]])
{
cell = (MainTableViewCell *)view;
}
}
}
Try customizing the cell inside tableView: willDisplayCell: method, something like this:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [UIColor redColor];
}
You need to change the tableView cell's contentView, not the cell's background view.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.contentView.backgroundColor = [UIColor redColor];
}
to have total control on the customisation of your cells, I prefer better to override the cell view,
create a new class for your cell view, that gets called by the UITableView,
later when i get to my work computer if you havent found your answer I will post some sample code,
once you see how it works is pretty easy
you could as well place an image for your cell background, and place different labels and images, buttons, textfields in custom places of your cell,
EDIT>>
the code! [is overkill just to change the background, but if you want to really customise your cell, this is the way to go!]
in your CustomCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UITableViewCell {
UILabel *_kLabel;
UILabel *_dLabel;
}
#property (nonatomic, retain) UILabel *kLabel;
#property (nonatomic, retain) UILabel *dLabel;
- (void) initLabels;
#end
in your CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize kLabel = _kLabel;
#synthesize dLabel = _dLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
CGRect popUpImageBgndRect = CGRectMake(0, 0, 942, 44);
UIImageView *popUpImageBgnd = [[UIImageView alloc] initWithFrame:popUpImageBgndRect];
[popUpImageBgnd setImage:[UIImage imageNamed:#"tableCellBgnd.png"]];
popUpImageBgnd.opaque = YES; // explicitly opaque for performance
[self.contentView addSubview:popUpImageBgnd];
[popUpImageBgnd release];
[self initLabels];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+10 ,10, 200, 20);
self.kLabel.frame = frame;
frame= CGRectMake(boundsX+98 ,10, 100, 20);
self.dLabel.frame = frame;
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void) initLabels {
self.kLabel = [[[UILabel alloc]init] autorelease];
self.kLabel.textAlignment = UITextAlignmentLeft;
self.kLabel.backgroundColor = [UIColor clearColor];
self.kLabel.font = [UIFont fontWithName:#"FS Albert" size:16];
self.kLabel.textColor = [UIColor colorWithRed:51.0f/255.0f green:51.0f/255.0f blue:51.0f/255.0f alpha:1];
self.dLabel = [[[UILabel alloc]init] autorelease];
self.dLabel.textAlignment = UITextAlignmentLeft;
self.dLabel.backgroundColor = [UIColor clearColor];
self.dLabel.font = [UIFont systemFontOfSize:16];
self.dLabel.textColor = [UIColor colorWithRed:51.0f/255.0f green:51.0f/255.0f blue:51.0f/255.0f alpha:1];
[self.contentView addSubview:self.kLabel];
[self.contentView addSubview:self.dLabel];
}
-(void) dealloc {
[_kLabel release];
[_dLabel release];
[super dealloc];
}
#end
And in your ViewController.m
YourViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
}
ENJOY!!
;)
try setting the cells backgroundColor property, worked for me cell.backgroundColor=[UIColor blueColor];
Please try this, it works for me.
UIView *bgView = [[UIView alloc] initWithFrame:cell.frame];
bgView.backgroundColor = [UIColor greenColor];
cell.backgroundView = bgView;
[bgView release];
As #Westley mentioned;
You need to change the tableView cell's contentView, not the cell's background view.
This is how you should do it:
if(index == conditionYouWant)
{
cell.contentView.backgroundColor = [UIColor whiteColor];
}
else
{
cell.contentView.backgroundColor = [UIColor colorWithRed:0.925 green:0.933 blue:0.937 alpha:1.0];
}
Hope it helps you guys out
Be sure you didn't already set the content view's background color in the Storyboard. If you did, changing the cell.backgroundColor in code will make no difference, and you will go round and round in confusion (like I did).
cell.backgroundColor = [UIColor redColor];
in swift 3 you can use
cell.backgroundcolor = UIColor.white

How to add a footer to the UITableView?

I'me using this code to add a footer to the TableView. It has 20 sections, and each section a few rows. There's a titleForHeaderInSection, and sectionForSectionIndexTitle methods.
CGRect footerRect = CGRectMake(0, 0, 320, 40);
UILabel *tableFooter = [[UILabel alloc] initWithFrame:footerRect];
tableFooter.textColor = [UIColor blueColor];
tableFooter.backgroundColor = [self.theTable backgroundColor];
tableFooter.opaque = YES;
tableFooter.font = [UIFont boldSystemFontOfSize:15];
tableFooter.text = #"test";
self.theTable.tableFooterView = tableFooter;
[tableFooter release];
What am I doing wrong?
thanks,
RL
I'm specifically seeing in my code that
self.theTable.tableFooterView = tableFooter;
works and
[self.theTable.tableFooterView addSubview:tableFooter];
does not work. So stick to the former and look elsewhere for the possible bug.
HTH
You need to implement the UITableViewDelegate method
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
and return the desired view (e.g. a UILabel with the text you'd like in the footer) for the appropriate section of the table.
I used that and it worked Perfectly :)
UIView* footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 500)];
[footerView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"ProductCellBackground.png"]]];
self.tableView.tableFooterView = footerView;
[self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
[self.tableView setContentInset:(UIEdgeInsetsMake(0, 0, -500, 0))];
I know that this is a pretty old question but I've just met same issue. I don't know exactly why but it seems that tableFooterView can be only an instance of UIView (not "kind of" but "is member")... So in my case I've created new UIView object (for example wrapperView) and add my custom subview to it... In your case, chamge your code from:
CGRect footerRect = CGRectMake(0, 0, 320, 40);
UILabel *tableFooter = [[UILabel alloc] initWithFrame:footerRect];
tableFooter.textColor = [UIColor blueColor];
tableFooter.backgroundColor = [self.theTable backgroundColor];
tableFooter.opaque = YES;
tableFooter.font = [UIFont boldSystemFontOfSize:15];
tableFooter.text = #"test";
self.theTable.tableFooterView = tableFooter;
[tableFooter release];
to:
CGRect footerRect = CGRectMake(0, 0, 320, 40);
UIView *wrapperView = [[UIView alloc] initWithFrame:footerRect];
UILabel *tableFooter = [[UILabel alloc] initWithFrame:footerRect];
tableFooter.textColor = [UIColor blueColor];
tableFooter.backgroundColor = [self.theTable backgroundColor];
tableFooter.opaque = YES;
tableFooter.font = [UIFont boldSystemFontOfSize:15];
tableFooter.text = #"test";
[wrapperView addSubview:tableFooter];
self.theTable.tableFooterView = wrapperView;
[wrapperView release];
[tableFooter release];
Hope it helps. It works for me.
Initially I was just trying the method:
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
but after using this along with:
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
problem was solved. Sample Program-
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 30.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *sampleView = [[UIView alloc] init];
sampleView.frame = CGRectMake(SCREEN_WIDTH/2, 5, 60, 4);
sampleView.backgroundColor = [UIColor blackColor];
return sampleView;
}
and include UITableViewDelegate protocol.
#interface TestViewController : UIViewController <UITableViewDelegate>
These samples work well. You can check section and then return a height to show or hide section. Don't forget to extend your viewcontroller from UITableViewDelegate.
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if (section == 0)
{
// to hide footer for section 0
return 0.0;
}
else
{
// show footer for every section except section 0
return HEIGHT_YOU_WANT;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *footerView = [[UIView alloc] init];
footerView.backgroundColor = [UIColor blackColor];
return footerView;
}
Swift
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.backgroundColor = UIColor.black
return footerView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 {
// to hide footer for section 0
return 0.0
} else {
// show footer for every section except section 0
return HEIGHT_YOU_WANT
}
}
Swift 2.1.1 below works:
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let v = UIView()
v.backgroundColor = UIColor.RGB(53, 60, 62)
return v
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 80
}
If use self.theTable.tableFooterView = tableFooter there is a space between last row and tableFooterView.
[self.tableView setTableFooterView:footerView];
instead of
self.theTable.tableFooterView = tableFooter;
try
[self.theTable.tableFooterView addSubview:tableFooter];
I had the same problem but I replaced the following line in my header:
#interface MyController : UIViewTableViewController <UITableViewDelegate, UITableViewDataSource>
with this line and it works as expected:
#interface RequestViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
Notice the UIViewController.
Good luck :)
If you don't prefer the sticky bottom effect i would put it in viewDidLoad()
https://stackoverflow.com/a/38176479/4127670

How do I set UITableViewCellSelectionStyle property to some custom color?

I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the UITableViewCell Class Reference but there are only three constants defined for Selection style (Blue, Gray, None). I saw one application that used a different color than those defined in the reference.
How can we use a color other than those defined in the reference?
The best way to set the selection is to set the selectedBackgroundView on the cell when you construct it.
i.e.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"SelectedCellBackground.png"]] autorelease];
}
// configure the cell
}
The image used should have a nice gradient (like the default selection). If you just want a flat color, you can use a UIView instead of a UIImageView and set the backgroundColor to the color you want.
This background is then automatically applied when the row is selected.
Setting the selectedBackgroundView seems to have no effect when the cell.selectionStyle is set to UITableViewCellSelectionStyleNone. When I don't set the style is just uses the default gray.
Using the first suggestion that inserts the custom UIView into the cell does manipulate the cell but it doesn't show up when the cell is touched, only after the selected action is completed which is too late because I'm pushing to a new view. How do I get the selected view in the cell to display before the beginning of the selected operation?
If you have subclassed a UITableViewCell, then you can customise the various elements of the cell by overriding the following:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if(highlighted) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor clearColor];
}
[super setHighlighted:highlighted animated:animated];
}
EDIT for iOS7:
as Sasho stated, you also need
cell.selectionStyle = UITableViewCellSelectionStyleNone
I tried some of the above, and I actually prefer to create my own subclass of UITableViewCell and then override the touchesBegan/touchesCancelled/touchesEnded methods. To do this, ignore all the selectedBackgroundView and highlightedColor properties on the cell, and instead just set these colors manually whenever one of the above methods are called. For example, if you want to set the cell to have a green background with red text, try this (within your custom cell subclass):
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//Set backgorund
self.backgroundColor = [UIColor themeBlue];
//Set text
self.textLabel.textColor = [UIColor themeWhite];
//Call super
[super touchesBegan:touches withEvent:event];
}
Note that for this to work, you need to set:
self.selectionStyle = UITableViewCellSelectionStyleNone;
Otherwise, you'll first get the current selection style.
EDIT:
I suggest using the touchesCancelled method to revert back to the original cell colors, but just ignore the touchesEnded method.
Override didSelectRowAtIndexPath: and draw a UIView of a color of your choosing and insert it behind the UILabel inside the cell. I would do it something like this:
UIView* selectedView; //inside your header
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
selectedView = [[UIView alloc] initWithFrame:[cell frame]];
selectedView.backgroundColor = [UIColor greenColor]; //whatever
[cell insertSubview:selectedView atIndex:0]; //tweak this as necessary
[selectedView release]; //clean up
}
You can choose to animate this view out when it gets deselected and will satisfy your requirements.
Sublcass UITableViewCell and override setHighlighted:animated:
You can define a custom selection color color by setting the backgroundColor (see WIllster's answer):
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if(highlighted) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor clearColor];
}
[super setHighlighted:highlighted animated:animated];
}
You can define a custom background image by setting the backgroundView property:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if( highlighted == YES )
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"seasonal_list_event_bar_default.png"]];
else
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"seasonal_list_event_bar_active.png"]];
[super setHighlighted:highlighted animated:animated];
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
// Set Highlighted Color
if (highlighted) {
self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
} else {
self.backgroundColor = [UIColor clearColor];
}
}
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
// Add your Colour.
SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[self setCellColor:Ripple_Colour ForCell:cell]; //highlight colour
}
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
// Reset Colour.
SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[self setCellColor:Ripple_Colour ForCell:cell]; //normal color
}
- (void)setCellColor:(UIColor *)color ForCell:(UITableViewCell *)cell {
cell.contentView.backgroundColor = color;
cell.backgroundColor = color;
}
To add a custom color use the below code. And to make it transparent use alpha: 0.0
cell.selectedBackgroundView = UIView(frame: CGRect.zero)
cell.selectedBackgroundView?.backgroundColor = UIColor(red:0.27, green:0.71, blue:0.73, alpha:1.0)
If you use custom color and want to give it rounded corner look use:
cell.layer.cornerRadius = 8
Also, use this for better animation and feel
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}