如何设置一个整数值作为导航栏的标题?

How to set a integer value as the title of navigation bar?

基本上我想将变量的值设置为导航控制器中显示的标题。该变量称为 titleAmount,应表示 table 视图中的行数。

为此,我创建了变量 var titleAmount:String?

并在 numberOfRowsInSection 中添加了以下内容:

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let theIntegerValue :Int = feedItems.count
        let theStringValue :String = String(theIntegerValue)
        titleAmount = theStringValue
        return feedItems.count

    }

因为标题必须是一个字符串,而我的变量正在寻找一个字符串,所以我在上面添加了以下内容:

let theIntegerValue :Int = feedItems.count
let theStringValue :String = String(theIntegerValue)

feedItems.count的值转换成字符串

^^ This is probably where the issue is ^^

feedItems.count 显示我的 table 视图中的行数。 (我已经测试并确认它有效)

最后在viewDidLoad()中我添加了self.navigationItem.title = titleAmount来设置变量的值作为导航栏标题。

未显示任何内容该字段留空。有什么问题?

您不应尝试更新 numberOfRowsInSection 中的标题。在填充或更新 feedItems.

的任何地方更新标题

feedItems 中更新项目数量的任何地方都需要更新标题:

self.navigationItem.title = "\(feedItems.count)"

请记住,即使您在 viewDidLoad 中做了 self.navigationItem.title = titleAmount,对 titleAmount 的任何进一步更改都不会反映在标题中。

numberOfRowsInSection 将在 viewDidLoad 之后执行。如果您在 numberOfRowsInSection 中设置 titleAmount,那么当您之前访问它时,titleAmount 将为零。

如果您可以观察 feedItems 并在它们更改时更新标题,那应该可以解决您的问题。截至目前,我认为您遇到了操作顺序问题。

var feeditems: [FeedItem] = [FeedItem]() {
    didSet {
        self.navigationItem.title = "Available items: \(feedItems.count)"
        reloadData()
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return feedItems.count
}

这是一个精简版,但应该很容易为您的用例实施。确保 feedItems 设置正确。