【问题标题】:Change color of label with if statement使用 if 语句更改标签颜色
【发布时间】:2017-11-30 18:33:15
【问题描述】:

如果字符串 i

无法使用类型参数列表调用类型“Int”的初始化程序 '([字符串])'

请帮忙。

var percent_change_24hArray = [String]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell

        let PercentInt = Int(percent_change_24hArray)

        if PercentInt < 0 {
           cell.procentLabel.textColor = UIColor.red
        }

        cell.procentLabel.text = "\(percent_change_24hArray[indexPath.row])%"

        return cell
    }

【问题讨论】:

    标签: swift string int


    【解决方案1】:

    你可能想使用

    let PercentInt = Int(percent_change_24hArray[indexPath.row])
    

    现在您收到的整数是可选的,因为并非所有字符串都可以转换为整数。作为开发人员,您要么知道这实际上永远不会发生,在这种情况下,您应该在行尾添加!。如果它可能发生,您必须使用适合您需要的if let 结构安全地解开可选项。

    【讨论】:

    • 当然这是假设percent_change_24hArray数组中的每个元素恰好有一行。
    • 谢谢,但我现在有一个不同的问题。它表示该值为 nil,但该值不是 nil,因为 cell.procentLabel.text = "\(percent_change_24hArray[indexPath.row])%" 表示例如 -17。
    • 使用if let PercentInt = Int(percent_change_24hArray[indexPath.row]), PercentInt &lt; 0 {...}
    • @Danjhi 您必须处理生成的可选选项。请查看 Annjawn 的评论或更新的答案。
    猜你喜欢
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多