Swift - TableView, change font of even rows to bold - swift

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.

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 tableview cell change width frame not work

This is my code but not work!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyChatCell
var frame = cell.frame
if(indexPath%2 == 0){
frame.size.width = CGFloat(200)
} else {
frame.size.width = CGFloat(100)
}
cell.frame = frame
return cell
}
I want change cell width to 100 or 200 per cell
But frame.size.width not work
You can't change that, because all cells in a table view must have the same width, but can have different heights if needed.
However, you can try to make the table view's .backgroundColor transparent, and maybe the content view of the cell, than add another "wrapper view" on the cell's content view and make it have different widths. It will create the "visual impression" that cells indeed have different widths.

Checking If every row in table view have image hidden or not

Is there any way to check inside a function : func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) If rest of the rows ( instead of the first one ) have image hidden or not.
If images of rows which are greater then indexPath.row - 0 are all hidden or not.
So basically I would like to get the first row ( image ) of the table view hidden when the rest one are hidden as well. The simple check boxes.
This how I'm hiding them :
let row = indexPath.row
if row > 0 {
UIView.animate(withDuration: 0.5, animations: {
let currentCell = self.engineStatusTableView.cellForRow(at: indexPath) as! DropDownViewCell
if !currentCell.checkMark.isHidden {
currentCell.checkMark.isHidden = true
} else {
currentCell.checkMark.isHidden = false
}
})
}
Thanks in advance!
It's generally not a good idea to keep your state inside of cells. Cells are reused and somewhat expensive to create, so you want to let UITableView control the creation and manage their reuse.
But, hopefully, your datasource knows if the checkmark is supposed to be hidden or not and you can ask it without having to create a cell to do that.

Swift TableView cell doesn't fit into 1 row

I'm working on a swift project. I have a tableview that loads the data correctly. However, I have many cells for each row and it doesn't fit into the iphone screen, and got cut off the screen. I would like to have some cells go on to the next line instead of not showing on the screen. How to do that? Thanks.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ResultTableViewCell
//cell.textLabel?.numberOfLines = 0
//cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
let category: Category = categories[indexPath.row]
cell.lblName.text = category.name
cell.lblQty.text = category.qty
cell.lblSub.text = category.sub
cell.lblSub2.text = category.sub2
cell.lblCountry.text = category.country
cell.lblState.text = category.state
cell.lblCity.text = category.city
return cell
}
On my screen, it can only fit 5 columns, and the rest gets cut off. I want to show each row in 2 lines. The first line will display the name, qty, sub, sub2 and the next line will display country, state and city.
It doesn't tell us much without seeing the layout of your cells and some example screens presenting the issue. But it's possible that you would want to look at autoresizing cells and UITableViewAutomaticDimension.

iOS8 Swift - Problems dynamically resizing tableview cells

Here's what my application looks like currently.
You'll see that when the subtitle text label is only one line is resizes correctly, but when there's multiple lines it gets all messed up. I think this has to do with the constraints possibly? Right now I'm using the auto-layout constraints. You can see them in the screenshot. Here's the code that creates my cells.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> DealCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Deal Cell", forIndexPath: indexPath) as DealCell
let currentBar = bars[indexPath.row] as BarAnnotation
cell.barName.text = currentBar.name
cell.deal.text = currentBar.deal
cell.distanceToBar.text = String(format: "%.3f mi", currentBar.distance)
// Set the height of the table view cells
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0;
return cell
}
Any ideas?
Use tableView:heightForRowAtIndexPath: function in the UITableViewDelegate.
Using this you can individually set the height of each row separately.
For more information : https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/index.html#//apple_ref/occ/intfm/UITableViewDelegate/tableView:heightForRowAtIndexPath:
Or you can use auto layout settings like in this article.
http://useyourloaf.com/blog/2014/02/14/table-view-cells-with-varying-row-heights.html