TableView every other cell one color - swift

Is there a way to color every other cell one color on a tableView? I tried looking into the properties for my tableView but were not able to find anything.
I want it like this:
tableview
cell - white
cell - gray
cell - white
cell - gray
etc...

One line code, if you want
cell.backgroundColor = indexPath.row % 2 == 0 ? .white : .gray

The easiest way will be to do this programmatically in your cellForRowAt function:
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.white
} else {
cell.backgroundColor = UIColor.gray
}

Related

Set Background Color of specific CollectionView Cells according to IndexPath

I'm pretty new to Swift and programming in general, so sorry for the simple question:
I want to develop a calendar that uses an (horizontally scrollable) UICollectionView as interface. Every cell of the UICollectionView is supposed to have a label with the number of the respective day and the weekday.
For this purpose I have an dateArray that stores the date-objects. The setupCell- method is putting the respective data onto the labels of the UICollectionViewCell.
Cells that show Sundays should be highlighted by having a different background-color than the other cells.
I tried to implement this functionality in the cellForItemAt - method, but got stuck there.
My function looks like this:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCollectionViewCell.identifier, for: indexPath) as! MyCollectionViewCell
let dayFormatter = DateFormatter()
let weekdayFormatter = DateFormatter()
dayFormatter.dateFormat = "dd"
weekdayFormatter.dateFormat = "EEE"
cell.setupCell(day: dayFormatter.string(from: dateArray[indexPath.item]), weekday: weekdayFormatter.string(from: dateArray[indexPath.item]))
if Calendar.current.component(.weekday, from: dateArray[indexPath.item]) == 1 {
cell.backgroundColor = UIColor.gray
}
return cell
}
With this function the Sundays are highlighted as planned, but only as long as I don't scroll. After some scrolling at the end all cells will be highlighted.
I'm thankful for every hint to solve the issue.
The UICollectionViewCells are being reused. Hence the name dequeueReusableCell. This means that, for example, the cell at index 0 is the same cell as at index 30. When you have set the color of the cell at index 0 to UIColor.gray, the cell at 30 will also be gray, unless you set it to another color. Because all cells are going to be reused, and all cells will eventually be a "Sunday" at some point, they will all become colored.
There is an easy fix for this, do not only set a color for the ones you want to have a color but also do the opposite.
For example:
if Calendar.current.component(.weekday, from: dateArray[indexPath.item]) == 1 {
cell.backgroundColor = UIColor.gray
} else {
cell.backgroundColor = UIColor.white
}
I haven't tried it myself before, but there seems to be another way to achieve this as well. You could also implement the prepareForReuse() (docs) method in the UICollectionViewCell itself. You could do this by adding the following to the cell:
override func prepareForReuse() {
super.prepareForReuse()
backgroundColor = UIColor.white // Or set to another color you want
}
Another method would be to set the backgroundColor in the setupCell() you created for your cell. This will be called every time a cell is reused, so this might be an excellent place to do this as well. Just apply the same logic as above (if Sunday -> gray, else -> white).

Swift - Custom cell width and height for textlabel and detailTextLabel

I wanna manage the long text in textlabel and detailtextlabel for the cells in UITableview because if the textlabel has a long text the detailedtextlabel truncate with "..." and viceversa.
Here's the problem:
So I wanna know if there's a way to manage the space between textlabel and detailtextlabel so there's no truncate and give them more lines. I tried with:
...
if tableData[indexPath.row].clave.count > 6 {
cell?.detailTextLabel?.numberOfLines = 5
cell?.textLabel?.numberOfLines = 5
} else {
cell?.detailTextLabel?.numberOfLines = 1
}
cell?.textLabel?.text = nueva_cadena_string
cell?.detailTextLabel?.text = tableData[indexPath.row].clave
cell?.textLabel?.textColor = UIColor.brown
cell?.textLabel?.font = UIFont.boldSystemFont(ofSize: 15.0)
cell?.textLabel?.lineBreakMode = .byWordWrapping
return cell!;
But it doesn't work very well, it seems to give them just 2 lines, not 5 and I can't change the width for the textlabel and detailtextlabel.
Try making your cell custom as this:
Try setting the tableviews row dimension to automatic
yourTableView.rowHeight = UITableViewAutomaticDimension
yourTableView.estimatedRowHeight = 80.0
try setting both textlabels number of lines either in the storyboard or in code to 0 as then they will all have the amount of lines they need.
You can subclass UITableViewCell and override the layoutSubviews() method. You will need to change the layout of textLabel and detailTextLabel there. Remember that these elements lie inside contentView, not in the cell itself.
But better you add two custom labels on the Storyboard and configure them as you want. It's easier.

How to keep tablecells from inheritiing in Swift

I'm trying to generate cells in my table view, each with dynamically allowed buttons on the right-hand side; some with 2 buttons, some with 4 buttons. The problem is, though the table view loads as I'd like, upon scrolling around, the cells end up all having 4 buttons - even the ones that only had two before hand.
What am I doing wrong?
Here is my code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row][0]
cell.accessibilityLabel = self.items[indexPath.row][bigSort]
cell.selectionStyle = .None
for x in 0..<4
{
let button = UIButton()
let marginStart = w - tickWidthInCell * 4 - 9 + (tickWidthInCell + 2) * x
let margin = CGFloat(marginStart)
button.frame = CGRectMake(margin, CGFloat(cellHeightMargin), CGFloat(tickWidthInCell), CGFloat(tickHeightInCell))
button.layer.borderColor = GRAY.CGColor
if (self.items[indexPath.row][1] == "Special" && x % 2 != 0)
{
button.backgroundColor = UIColor.clearColor()
button.layer.borderColor = UIColor.clearColor().CGColor
//button.hidden = true
}
else
{
button.addTarget(self, action: #selector(cellButtonClicked), forControlEvents: .TouchUpInside)
button.backgroundColor = UIColor(netHex:0x222222)
button.layer.borderWidth = 1
}
cell.contentView.addSubview(button)
}
return cell
}
It's because tableview reuses the cells you define.
To get control over how the reusing should happen, in your custom UITableViewCell override prepareForReuse. And always reset them the state you want to be, like setting the cell to only have 2 buttons)
Or in cellForRowAtIndexPath you can handle both cases to have either 2 buttons or 4.
(when you are specifying that you want 2 buttons make sure that you hide the other 2)

Swift table view with a cell that is transparent and shows background image

I have tried to do so:
added an orange view behind a table view.
for a certain cell hide with alpha = 0 all her elements
tried to make the cell transparent so that it shows the orange view behind the table view while it scrolls:
cell2.backgroundColor = UIColor.clearColor()
cell2.backgroundView = nil
cell2.backgroundView?.backgroundColor = UIColor.clearColor()
tried to make the table view transparent so that it allows the orange view behind to be showed
tableView.backgroundColor = UIColor.clearColor()
tableView.opaque = false
tableView.backgroundView = nil
However I can not see the orange view behind the table view when I scroll and get to my cell, it just shows a grey cell.
Can somebody give me any hint to what else I should do?
Thank you
In your viewDidLoad(), add the code immediately below to set the tableView's background color.
tableView.backgroundColor = UIColor.clearColor()
In your cellForRowAtIndexPath method, use something similar to the code below to set a given cell's backgroundColor to be transparent, where the value 2 is the row of the cell you'd like to change.
switch indexPath.row {
case 2:
cell.backgroundColor = UIColor.clearColor()
default:
print("NOT Clear")
}

Swift - TableView, change font of even rows to bold

I have a tableview and i want to change the font of even rows, Here is my code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "ProductListTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ProductListTableViewCell
let product = productList[indexPath.row]
cell.productName.text = product.name
cell.productPrice.text = "\(product.price) manat"
if(indexPath.row % 2 == 0) {
cell.productName.font = UIFont.boldSystemFontOfSize(13.0)
cell.productPrice.font = UIFont.boldSystemFontOfSize(13.0)
}
return cell
}
when i run my code, at the beginning everything works correctly, when i scroll my table view, all new rows appeared on screen becomes bold, both even and old rows. What am i doing wrong?
Remember that a table view reuses cells. That's why you get them from a method named dequeueReusableCellWithIdentifier(_:forIndexPath:).
You set the font to bold when it's an even-numbered row, but you don't set it back to normal when it's an odd-numbered row. If the cell was previously used for an even-numbered row, and is now being used for an odd-numbered row, it still has a bold font.
let weight = (indexPath.row % 2 == 0) ? UIFontWeightBold : UIFontWeightRegular
let font = UIFont.systemFontOfSize(13, weight: weight)
cell.productName.font = font
cell.productPrice.font = font
Your reusable cells are all being set to bold. Add an else to the if row % 2 == 0 to set the cell back to normal font when it is used in an odd row.