when you tap on a cell the row gets selected and highlighted.Now what i want to do is disable the highlighting but allow the selection.Is there a way around it.There is question that answers this but it disables both the selection and highlighting.
You can just set the cell's selection style to "None" from Storyboard:
Or from code:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
For Swift 3:
cell.selectionStyle = UITableViewCellSelectionStyle.none
For Swift 4 & above:
cell.selectionStyle = .none
Change UITableViewCell's selectedBackgroundView color to transparent.
let clearView = UIView()
clearView.backgroundColor = UIColor.clearColor() // Whatever color you like
UITableViewCell.appearance().selectedBackgroundView = clearView
or to set for a specific cell:
cell.backgroundView = clearView
Try setting cell selection style to None -
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
This will solve your problem
For Swift 3.0:
cell.selectionStyle = .none
For Swift:
UITableViewCell.selectionStyle = UITableViewCellSelectionStyle.None;
Or when you subclass a cell in swift:
class CustomCell : UITableViewCell {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
selectionStyle = .None
}
}
in swift 3
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
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)
}
For those looking for a programmatic way in Swift 3
cell.selectionStyle = UITableViewCellSelectionStyle.none
You can set the selection property of the cell itself in the storyboard
For Objc:
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
- (void)viewDidLoad {
[super viewDidLoad];
_tableView.allowsSelection = YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
.. .. .. ..
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
. . . . ..
}
For Swift 5 the best way is:
cell.selectionStyle = .none
Here is the solution for swift 3,works even in editing mode
cell.selectionStyle = .gray
cell.selectedBackgroundView = {
let colorView = UIView()
colorView.backgroundColor = UIColor.black.withAlphaComponent(0.0)
//change the alpha value or color to match with you UI/UX
return colorView
}()
Related
How to make the tableview cell that has been selected to no color as Vine App.
I've tried it but with clear color but the cell white out when it is get selected
Vine example no background color change
https://vid.me/tfkk
My project : Cell color changed even if it was set to clearColor
https://vid.me/awCq
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! DiscvoerTVC
let colorView = UIView()
colorView.backgroundColor = nil
UITableViewCell.appearance().selectedBackgroundView = colorView
if indexPath.row == 0 {
cell.DiscoverViewColor.backgroundColor = UIColor.grayColor()
cell.DiscoverViewLabel.text = "USMLE CK"
cell.backgroundColor = UIColor.grayColor()
cell.layer.cornerRadius = 20.0
cell.layer.masksToBounds = true
let colorView = UIView()
colorView.backgroundColor = nil
UITableViewCell.appearance().selectedBackgroundView = colorView
}
You mean cell's selection style? If so, set its selection style to none
cell.selectionStyle = .None;
I have a piece of code as follows (I have omitted the unnecessary parts):
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell? {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
self.tableView.allowsMultipleSelection = true
self.tableView.separatorColor = UIColor.blueColor()
self.tableView.tableFooterView = UIView(frame:CGRectZero)
return cell
}
When I choose adjacent cells, the separating line between them disappears, which is not what I want. Is it possible to avoid this?
When you select any cell separator disappears. The solution is to add custom separators.
Try move the code below to viewDidLoad as it just need to be executed once:
self.tableView.allowsMultipleSelection = true
self.tableView.separatorColor = UIColor.blueColor()
self.tableView.tableFooterView = UIView(frame:CGRectZero)
I change the background color of the UITableViewCells in the tableView:cellForRowAtIndexPath method
if(indexPath.row % 2 == 0){
cell.backgroundColor = ...
} else{
cell.backgroundColor = ...
}
But that only change the color of the cell amount specified in tableView:numberOfRowsInSection (As seen in the attached picture, there are white cells after the first four)
Is it possible to change the color of all cells that are displayed on screen?
Open Storyboard
Select your UITableView
Open Attribute inspector
Scroll to View group
Select background color for entire table.
If you want the cell background color to continue to alternate, then you need to lie about how many rows are in the table. Specifically, in tableView:numberOfRowsInSection you need to always return a number that will fill the screen, and in tableView:cellForRowAtIndexPath, return a blank cell for rows that are beyond the end of the table. The following code demonstrates how to do this, assuming that self.dataArray is an NSArray of NSStrings.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ( self.dataArray.count < 10 )
return( 10 );
else
return( self.dataArray.count );
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SimpleCell"];
if ( indexPath.row % 2 == 0 )
cell.backgroundColor = [UIColor orangeColor];
else
cell.backgroundColor = [UIColor redColor];
if ( indexPath.row < self.dataArray.count )
cell.textLabel.text = self.dataArray[indexPath.row];
else
cell.textLabel.text = nil;
return cell;
}
Try like this:-
self.tableView.backgroundView.backgroundColor = [UIColor blueColor];
In swift, you can change tableview background color or you can set image to tableview background color like this;
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)
self.tableView.backgroundColor = UIColor.clearColor()
}
// change cell text color and background color
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor.clearColor()
}
I used this to color alternate cell in a table view
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row % 2 == 0)
{
cell.backgroundColor = UIColor.grayColor()
}
else
{
cell.backgroundColor = UIColor.whiteColor()
}
}
You need to set the tableview's backgroundView to nil and its backgroundColor to the desired color.
For SWIFT
Thanks to #Irshad Qureshi I was able to get alternating background colors for my prototype cells by adding the following in my cellForRowAtIndexPath:
if (indexPath.row % 2 == 0)
{
cell!.backgroundColor = UIColor.groupTableViewBackgroundColor()
}
else
{
cell!.backgroundColor = UIColor.whiteColor()
}
Swift 5 and up
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//Set Clear Backcolor
//cell.backgroundColor = .clear
//or in your case
if ( indexPath.row % 2 == 0 )
cell.backgroundColor = .orange
else
cell.backgroundColor = .red
}
I have a UICollectionView that I have created programmatically. I would like for the collection view to behave in the following way:
1. User touches cell
2. Cell background color changes
3. User releases touch
4. Cell background color changes
This should be a quick color change that happens just before the selector related to the tap action is executed in which the viewcontroller containing the collection view is popped off the stack.
I have been looking at this question: UICollectionView cell change background while tap
in which there is the following summary of methods to use for this purpose:
// Methods for notification of selection/deselection and highlight/unhighlight events.
// The sequence of calls leading to selection from a user touch is:
//
// (when the touch begins)
// 1. -collectionView:shouldHighlightItemAtIndexPath:
// 2. -collectionView:didHighlightItemAtIndexPath:
//
// (when the touch lifts)
// 3. -collectionView:shouldSelectItemAtIndexPath: or - collectionView:shouldDeselectItemAtIndexPath:
// 4. -collectionView:didSelectItemAtIndexPath: or -collectionView:didDeselectItemAtIndexPath:
// 5. -collectionView:didUnhighlightItemAtIndexPath:
I am assuming I only need to implement one of the above methods from 'when touch begins' and 'when touch ends.' But no matter what I do, it appears that a background color changes and then remains changed. Here is an example of something I attempted which did not work:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//pop vc
}
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor redColor];
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor greenColor];
}
This results in the cell background color being changed only to red. I also looked at this question: UICollectionView Select and Deselect issue and tried implementing [UICollectionView selectItemAtIndexPath:animated:scrollPosition:] and calling it inside of didSelectItemAtIndexPath, but this did not work either. Collection view data source and delegate are set.
The problem is that you are changing the color on highlight and changing it back on deselect instead that on unhighlight
You should simply change this:
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor greenColor];
}
to this:
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor greenColor];
}
Also, if you don't want to wait a bit before getting your highlight happen you should set the delaysContentTouches property of the collection view to NO
Edit: also ensure that you call
[collectionView deselectItemAtIndexPath:indexPath animated:NO];
inside the -didSelectItemAtIndexPath method
Swift 3 version
Add the following two methods to your view controller class:
// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.red
}
// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.green
}
See here for help in setting up a basic collection view in Swift.
Edit: Answer in Swift 3
var selectedIndex = Int ()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.backgroundColor = selectedIndex == indexPath.row ? UIColor.green : UIColor.red
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
selectedIndex = indexPath.row
self.yourCollctionView.reloadData()
}
Here is my solution. And I'm sure it really works.
I provide three methods to highlight a cell (selectedBackgroundView, tint cell.contentView and tint a special area).
How to use:
1. just inherit BaseCollectionViewCell and do nothing;
2. inherit and set specialHighlightedArea = UIView(), and contentView.addSubView(specialHighlightedArea), then layout it or add constraint to use Auto Layout;
3. if you don't need highlight effect, just write a method named 'shouldHighlightItemAtIndexPath' defined by UICollectionViewDelegate and make it return false, or set cell.shouldTintBackgroundWhenSelected = false and set specialHighlightedArea = nil and remove it from superView.
/// same with UITableViewCell's selected backgroundColor
private let highlightedColor = UIColor(rgb: 0xD8D8D8)
/// you can make all your collectionViewCell inherit BaseCollectionViewCell
class BaseCollectionViewCell: UICollectionViewCell {
/// change it as you wish when or after initializing
var shouldTintBackgroundWhenSelected = true
/// you can give a special view when selected
var specialHighlightedArea: UIView?
// make lightgray background display immediately(使灰背景立即出现)
override var isHighlighted: Bool {
willSet {
onSelected(newValue)
}
}
// keep lightGray background until unselected (保留灰背景)
override var isSelected: Bool {
willSet {
onSelected(newValue)
}
}
func onSelected(_ newValue: Bool) {
guard selectedBackgroundView == nil else { return }
if shouldTintBackgroundWhenSelected {
contentView.backgroundColor = newValue ? highlightedColor : UIColor.clear
}
if let area = specialHighlightedArea {
area.backgroundColor = newValue ? UIColor.black.withAlphaComponent(0.4) : UIColor.clear
}
}
}
extension UIColor {
convenience init(rgb: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0xFF00) >> 8) / 255.0, blue: CGFloat(rgb & 0xFF) / 255.0, alpha: alpha)
}
}
Simple binary logic solution. Works with Swift 3 and 4:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt
indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CategoryCell
let lastCellColor = cell.backgroundColor
if cell.isSelected {cell.backgroundColor = .green} else {cell.backgroundColor = lastCellColor}
}
Add all the subviews inside contentView,
use backgroundView and selectedBackgroundView from UICollectionViewCell. Do not set contentView.backgroundColor.
// Add this inside your cell configuration.
private func setupSelectionColor() {
let backgroundView = UIView()
backgroundView.backgroundColor = .white
self.backgroundView = backgroundView
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = .orange
self.selectedBackgroundView = selectedBackgroundView
}
// Add the deselection inside didSelectCallback
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
}
I realize that iOS 7 has not officially been released and we should not discuss it BUT I am going crazy trying to figure out this problem. On iOS 6, my table view was transparent and looked great. First time running iOS 7, and the background is white.
I have tried making the table backgroundColor, cell color etc etc to UIColor clearColor but have no change.
How to fix this problem?
// Fix for iOS 7 to clear backgroundColor
cell.backgroundColor = [UIColor clearColor];
cell.backgroundView = [[UIView new] autorelease];
cell.selectedBackgroundView = [[UIView new] autorelease];
in cellForRowAtIndexPath
Also, make sure that your tableview actually has transparent background (in storyboard):
Put this:
cell.backgroundColor = [UIColor clearColor];
In this section:
cellForRowAtIndexPath
Try setting backgroundView to nil first.
[self.tableView setBackgroundView:nil];
[self.tableView setBackgroundColor:[UIColor clearColor]];
Not sure if this is a change in documentation with iOS7 or has always been there and just did not affect background color, but per UITableView Class Reference #property backgroundView
"You must set this property to nil to set the background color of the table view."
edit: corrected code syntax
This has been answered, but incorrectly in a lot of ways.
You need to implement the below delegate method:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
[cell setBackgroundColor:[UIColor clearColor]];
}
You can't put the fix in cellForRowAtIndexPath because that is after the cell is rendered, and it will flash a white background before the background gets set to clear (on slower devices).
Use this delegate method and your problems are solved!
Actually the officially correct place to change cell background color is different according to documentation (UITableViewCell Class Reference):
Whether you use a predefined or custom cell, you can change the cell’s
background using the backgroundView property or by changing the
inherited backgroundColor property. In iOS 7, cells have a white
background by default; in earlier versions of iOS, cells inherit the
background color of the enclosing table view. If you want to change
the background color of a cell, do so in the
tableView:willDisplayCell:forRowAtIndexPath: method of your table view
delegate.
swift 3, 4 and 5
cell.backgroundColor = UIColor.clear
This is quite a frustrating problem. Here's my current solution:
Add this to your UITableViewCell subclass.
- (void)didMoveToSuperview {
[super didMoveToSuperview];
self.backgroundColor = [UIColor clearColor];
}
This did only work for me when i edited a clear background color for each cell and a clear color for the table itself.. BOTH PROGRAMMATICALLY
to set the clear color for the table:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initMenu()
myTableView.backgroundColor = UIColor.clearColor()
}
to set the color for the cells:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tablecellid", forIndexPath: indexPath)
cell.backgroundColor = UIColor.clearColor()
return cell
}
This worked for me in iOS7+:
self.tableView.backgroundColor =[UIColor blueColor];
self.tableView.opaque = NO;
self.tableView.backgroundView = nil;`
and then in cellForRowAtIndexPath:
cell.backgroundColor = [UIColor clearColor];
try this code snippet
cell.contentView.backgroundColor = [UIColor clearColor];
cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5];
First set
tableView.backgroundColor = [UIColor clearColor];
Second set
tableCell.backgroundColor = [UIColor clearColor];
One thing to nice. The default color of UITable seems to be white (I don't know why)
But better change that.
create IB Outlet for table view
#IBOutlet weak var yourTable : UITableView!
in view load
override func viewDidLoad() {
yourTable.delegate = self
yourTable.dataSource = self
yourTable.backgroundColor = UIColor.clearColor()
}
if you want to clear color of Cell also do this in
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell.backgroundColor = UIColor.clearColor()
}
In my app, I had to set the backgroundColor on my UITableViewCell class to [UIColor clearColor] color when I updated for iOS 7.
Try
[myTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[myTable setSeparatorInset:UIEdgeInsetsZero];
And
cell.backgroundColor = [UIColor clearColor];
In my case the cell was created using a xib. it seems like interface builder on xcode5 has trouble setting clearColor to the cell.backgroundColor.
All I needed to do was indeed to set
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// get the cell from the nib
//then force the backgroundColor
cell.backgroundColor = [UIColor clearColor]
return cell;
}
Just select Clear Color on View Background for the table and for the cell also.
swift 3
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.clear
}
// Fix iOS 7 clear backgroundColor compatibility
// I Think this two lines only are enough
cell.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = [[UIView new] autorelease];
In swift 3
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath)
cell.backgroundColor = .clear
cell.backgroundView = UIView()
cell.selectedBackgroundView = UIView()
return cell
}
Set
tableView.backgroundColor = [UIColor clearColor];
in viewDidLoad.
if this is not working, try:
tableView.backgroundView = nil;