简体   繁体   中英

Programmatically change the image of a button in a table cell

//The objectsAry is NSManagedObjects

//main view controller

   var nowImg = UIImage(named: "img30.png")

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var NuTblCellInst = NuTableViewCell()

        var maincell:UITableViewCell = self.mainList.dequeueReusableCellWithIdentifier("maincell") as NuTableViewCell

        maincell.textLabel.text = self.objectsAry[indexPath.row].valueForKey("itemname") as? String

        //NuTblCellInst.doImgLoad(nowImg!)
        //uncomment the line above = fatal error: unexpectedly found nil while unwrapping an Optional value
        // it doesn't matter if i use the method or use NuTblCellInst.btnWImg.setBackgroungImage directly (unwrapping error either way)

        return maincell
    }

// custom tableview cell class

class NuTableViewCell: UITableViewCell {

    @IBOutlet weak var btnWImg: UIButton!

    var nowImg = UIImage(named: "img30.png")

    func doImgLoad(theImg: UIImage) {
        btnWImg.setBackgroundImage(theImg, forState: UIControlState.Normal)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        //doImgLoad(nowImg!)
        //uncomment the line above and it loads the image to the button no problem
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

I'm populating a reusable cell w/text as above, but not sure how to access the image (or background image) for a button placed in the table cell using storyboard where the image will vary with the table row.

From '... will vary with the table row,' it sounds like you're building a reusable template cell.

  1. CustTableViewCell must be derived from UITableViewCell
  2. Editing your template cell in the storyboard editor...
    • in the Identity Inspector, set the class to your custom class
    • create an outlet for the button in CustTableViewCell
  3. In tableview:cellForRowAtIndexPath
    • create/dequeue maincell as a CustTableViewCell -- not UITableViewCell
    • set properties on the button via the outlet
    • return your instance (of course :-) )

cf custom uitableviewcells in storyboard

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