简体   繁体   中英

Manipulating tags inside reusable cells?

From help on SO I managed to come up with this approach for a button inside a cell.

CellForRowAtIndexPath

    let cell = tableView.dequeueReusableCellWithIdentifier("buildCell", forIndexPath: indexPath) as! UITableViewCell

    let mapsbut = cell.viewWithTag(912) as! UIButton
    mapsbut.tag = indexPath.row
    mapsbut.addTarget(self, action: "mapsHit:", forControlEvents: UIControlEvents.TouchUpInside)

    return cell

ViewController

func mapsHit(sender: UIButton!){

    passBuild = buildings[sender.tag]
    performSegueWithIdentifier("mapSegue2", sender: self)

}

What happens now is when I scroll through the Table View I get a fatal error on the line:

let mapsbut = cell.viewWithTag(912) as! UIButton

with message: unexpectedly found nil while unwrapping an Optional value

So, what's happening is, the View Tag changes inside the function, and when I try to reference it in the next cell, 912 has been changed.

To counter this I add this line of code at the end of mapsHit function

sender.tag = 912

But now I need the following condition:

if the button isn't clicked, change tag to 912

which doesn't seem possible.

Is there any workaround?

Set up your custom cell like this:

buildingCell

class buildingCell: UITableViewCell {

    @IBOutlet weak var mapsbut: UIButton!

}

CellForRowAtIndexPath

    let cell = tableView.dequeueReusableCellWithIdentifier("buildCell", forIndexPath: indexPath) as! buildingCell

    cell.mapsbut.tag = indexPath.row
    cell.mapsbut.addTarget(self, action: "mapsHit:", forControlEvents: UIControlEvents.TouchUpInside)

    return cell

and leave your mapsHit function exactly the same.

This way you don't have to worry about the Tag for the initial reference so you won't run into any nil errors!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM