Reputation: 510
I`m having a problem and I created a simple mvp to show for you guys.
When I scroll on the table other index gets the color and the font.
Exemple:
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
var texto: [String] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
texto.append("Title 1")
texto.append("Content 1")
texto.append("Read More 1")
texto.append("Title 2")
texto.append("Content 2")
texto.append("Read More 2")
texto.append("Title 3")
texto.append("Content 3")
texto.append("Read More 3")
texto.append("Title 4")
texto.append("Content 4")
texto.append("Read More 4")
texto.append("Title 5")
texto.append("Content 5")
texto.append("Read More 5")
texto.append("Title 6")
texto.append("Content 6")
texto.append("Read More 6")
texto.append("Title 7")
texto.append("Content 7")
texto.append("Read More 7")
self.tableView!.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.texto.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell2")! as UITableViewCell
if [0,3].contains(indexPath.row){
cell.textLabel?.font = UIFont(name: "Helvetica", size: 28)
}
if [2,5].contains(indexPath.row){
cell.textLabel?.textColor = UIColor(hue: 0.575, saturation: 1, brightness: 0.89, alpha: 1.0)
}
cell.textLabel?.text = self.texto[indexPath.row]
return cell
}
}
In the cellForRowAtIndexPath
I write, if index of texto is 0 or 3 they get font changed, but when i use the scroll other index`s get the same font too.
Upvotes: 0
Views: 102
Reputation: 296
UITableViewCell
s get reused, so you will need to either:
A - Reset .font
and .textColor
to the default values after you dequeue the cell
or
B - Add an else
block to each if
statement that resets the .font
or .textColor
to the default value
Upvotes: 1
Reputation: 318814
Cells get reused. When you set a cell's attribute for one condition, you need to reset it for the other conditions. Update your code to something like this:
if [0,3].contains(indexPath.row){
cell.textLabel?.font = UIFont(name: "Helvetica", size: 28)
} else {
cell.textLabel?.font = // Some default font
}
if [2,5].contains(indexPath.row){
cell.textLabel?.textColor = UIColor(hue: 0.575, saturation: 1, brightness: 0.89, alpha: 1.0)
} else {
cell.textLabel?.textColor = // some default color
}
Upvotes: 2