【问题标题】:Programmatically change the image of a button in a table cell以编程方式更改表格单元格中按钮的图像
【发布时间】:2014-11-04 19:30:48
【问题描述】:

//objectsAry 是 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)
    }
}

我正在填充一个可重复使用的带文本的单元格,但不确定如何使用情节提要访问放置在表格单元格中的按钮的图像(或背景图像),其中图像将随表格行而变化。

【问题讨论】:

    标签: ios swift tableview


    【解决方案1】:

    从“...会随表格行变化”,听起来您正在构建一个可重用的模板单元格。

    1. CustTableViewCell 必须派生自 UITableViewCell
    2. 正在情节提要编辑器中编辑模板单元格...
      • 在 Identity Inspector 中,将类设置为您的自定义类
      • CustTableViewCell中的按钮创建一个出口
    3. tableview:cellForRowAtIndexPath
      • 创建/出列maincell 作为CustTableViewCell -- 不是 UITableViewCell
      • 通过插座设置按钮的属性
      • 返回您的实例(当然:-))

    cfcustom uitableviewcells in storyboard

    【讨论】:

    • 会回来的。可能还要等一下。那么,如果我已经返回了主单元,如何在 CFRAIP 中返回自定义类实例?
    • 你的 CFRAIP 现在是什么样子的?
    • 为答案添加了更多细节
    • 做了一些代码更改并添加了 cmets。我现在可能会调整 UI 方法并回到这个问题。
    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2016-07-17
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多