【问题标题】:Unable to change button image in uitableView无法更改 uitableView 中的按钮图像
【发布时间】:2016-02-11 07:19:36
【问题描述】:

我正在制作一个类似于堆栈溢出的论坛应用程序。有一个 UITableView 显示问题的答案,每个单元格(包含一个答案)还包含一个“正确答案”勾选按钮。在任何给定时间只能选择一个答案作为正确答案。正确答案标有绿色勾号,而其他答案标有灰色勾号(我有两个相同的图像,但颜色不同)。我正在尝试将其设置为当用户单击灰色的刻度按钮时,当前绿色按钮变为灰色,而被点击的灰色按钮变为绿色。

@IBOutlet weak var answeredTick: UIButton!

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    cell.answeredTick.tag = indexPath.row
}

@IBAction func answerTickPressed(sender: AnyObject) {
    guard let answeredTick = sender as? UIButton else { return }

    //indexOfOfficialAnswerId is the currently registered official ID
    if let buttonToMakeGrey = answeredTick.viewWithTag(self.indexOfOfficialAnswerId) as? UIButton {
        print("success!")
        buttonToMakeGrey.setImage(UIImage(named: "greyTick.png"), forState: UIControlState.Normal)

    } else {
        print("no success")
    }
}

但是它总是打印“没有成功”。 if 语句中 indexOfOfficialAnswerId 的值是正确的。我可以让灰色的 answerTicks 变成绿色,但我不能让绿色变成灰色。这是为什么呢?

更新:如果我点击绿色勾号,我似乎可以将绿色勾号设为灰色,但如果我点击任何灰色勾号则不行

【问题讨论】:

  • 顺便说一句,您还必须在 else 块中设置其他图像
  • 什么意思? @iAnurag

标签: ios swift uitableview uibutton


【解决方案1】:

你可以像这样找到带有绿色勾号的单元格:

NSIndexPath  *indexPath = [NSIndexPath indexPathForItem:self.indexOfOfficialAnswerId inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

然后使用你的:

cell.answeredTick.setImage(UIImage(named: "greyTick.png"), forState: UIControlState.Normal)

抱歉,Objective-C 代码

【讨论】:

  • Obc-C 没问题,我转换了它:)。我无法使用它,因为 indexOfficialAnswerId 未存储在单元格中。它被计算并存储为局部变量
  • 我是否更正了单元类中的函数 answerTickPressed ?然后您可以添加到单元格委托(到类,tableView 存储的位置)并在 answerTickPressed 中调用其方法。上面的代码在哪里。
  • 在单元类中是什么意思?
  • 据我了解,您有继承 UITableViewCell 的类,其中您有 answerTick 属性和 answerTickPressed 方法。还是没有?
  • 在该单元格类属性“delegate”中创建类似于 id 的东西。在该协议中,您将拥有一个功能,例如“correctAnswerWasChanged”。您有存储表格视图和创建单元格的类,例如,我将该类称为“A”。 “A”需要采用 CorrectAnswerProtocol。在哪里创建单元格,写 cel.delegate = self(其中 self 我们的类“A”)。最后在方法“answerTickPressed”中调用delegate.correctAnswerWasChanged
【解决方案2】:

在设置按钮图像或将其状态更改为选中后尝试重新加载该单元格。我想这可能是问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多