justinium justinium - 1 year ago 118
Swift Question

Loop through individual UITableViewCells in UITableView in order to edit text in cells

I am currently trying to loop through the cells of a UITableView in order to strikeout particular UILabels contained in the related viewController.

How would I go about doing this?

Context: The array specialBool contains 6 bools. The index position corresponds to a product that is either on special or not. If the bool is true then I want the label (previousPrice) in that particular product cell to be struck out... if it is false then the label should remain normal.

This is my code so far. It is incomplete:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! exploreTableView

cell.photo.image = globalVariable.images[indexPath.row]
cell.name.text = globalVariable.names[indexPath.row]
cell.price.text = globalVariable.prices[indexPath.row]
cell.unitPrice.text = globalVariable.unitPrice[indexPath.row]
cell.pPrice.text = globalVariable.previousPrice[indexPath.row]

var i = 0
while i < globalVariable.previousPrice.count {
if (globalVariable.specialBool[i] == true) {

// Strike through previous price
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: globalVariable.previousPrice[i])
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))
cell.pPrice.attributedText = attributeString;

} else {
cell.pPrice.text = globalVariable.previousPrice[i]

i += 1

return cell

Answer Source

You should first understand what are you doing and what you want to do. Get good understanding of UITableView

You should not need the while loop and also cellForRowAtIndexPath calls for each visible cells(These cells reused for other index paths).

//Remove while loop and var i = 0

//This will call for each visible cell so replace `i` with indexPath.row
if globalVariable.specialBool[indexPath.row] == true {
 // do your work here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download