如何基于UITableViewCell水龙头更新UINavigationItem?

时间:2019-08-16 00:27:06

标签: ios swift uitableview uinavigationitem

我正在创建一个测验应用程序,其中每个测验问题是一个分组的TableView,每个单元格都是一个答案选项,并且嵌入到导航控制器中。对于用户点击的每个正确答案,我希望他们的分数提高1。我已经在导航控制器中将分数标签设置为rightBarButtonItem。

这是我在viewDidLoad()中创建条形按钮项的条件:

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Score: \(score)", style: .plain, target: nil, action: Selector(("updateScore")))

我有一个模型类Question,其中包含一个数组questionsList,该数组包含以下属性:questionString,answers [],selectedAnswerIndex(nil)和correctAnswerIndex(int)

updateScore方法:

@objc func updateScore() {

        for question in questionsList {

            if question.selectedAnswerIndex == question.correctAnswerIndex {
                score += 1
            }
        }
    }

有什么想法吗?我尝试了另一种方法,即将得分标签放在footerview中,使用viewForFooterInSection作为表控制器,并将for循环放入我的didSelectRowAt方法中,但是得分标签也不会在那里更新。

1 个答案:

答案 0 :(得分:0)

更新score后,需要创建并分配一个新的条形按钮项目。您无法更新现有按钮的文本。

for循环之后,添加:

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Score: \(score)", style: .plain, target: nil, action: Selector(("updateScore")))

是的,它与您创建原始按钮时显示的代码相同。

更好的方法是更新您的score属性:

var score: Int = 0 {
    didSet {
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Score: \(score)", style: .plain, target: nil, action: Selector(("updateScore")))
    }
}

然后更新您的updateScore

@objc func updateScore() {
    var newScore = score
    for question in questionsList {
        if question.selectedAnswerIndex == question.correctAnswerIndex {
            newScore += 1
        }
    }

    score = newScore
}

然后更新viewDidLoad(或在任何地方)并删除当前调用以创建条形按钮项,只需执行以下操作:

score = 0 // or some other appropriate initial value