【问题标题】:Using Cell Tags and objectForKey in Swift在 Swift 中使用 Cell 标签和 objectForKey
【发布时间】:2015-08-30 13:09:57
【问题描述】:

我正在将我的项目从Objective-C 转换为Swift,并试图弄清楚如何在Swift 中编写它:

UILabel *tvLabel = (UILabel*) [cell viewWithTag:104];
tvLabel.text = [object objectForKey:@"tv"];

我已经尝试了一些不同的东西,比如:

    if let tvLabel = object?["tv"] as? String {
        cell?.textLabel?.text = cell.viewWithTag(4) as? UILabel
    }

...但他们都有错误,我似乎无法得到解决方案。

有什么想法吗?

【问题讨论】:

    标签: swift uitableview parse-platform swift2


    【解决方案1】:

    你可能想要这样的东西:

    if let tvLabel = cell?.viewWithTag(4) as? UILabel {
        tvLabel.text = object.objectForKey("tv") as! String
    }
    

    更安全的方式:

    if let tvLabel = cell?.viewWithTag(4) as? UILabel, let tvString = object?.objectForKey("tv") as? String {
        tvLabel.text = tvString
    }
    

    【讨论】:

    • 感谢您的回复,这看起来更接近我的需要,但我仍然收到错误 Cannot subscript a value of type PFObject。有什么想法吗?
    • 我更新了我的回复,这不是您之前的 Objective-c 代码的实际翻译
    • 如果我使用更新后的响应,它会出错并要求我使用! 或?,当我这样做时它会给我一个错误Cannot assign a value of type AnyObject? to a value of type String? 你知道为什么会这样吗?是吗?
    • 再次更新答案,添加as! String。不确定从objectForKey("tv") 返回什么样的对象,如果有任何返回的话。所以它返回AnyObject?(nil 或 AnyObject)。如果您想将其用作一个,则必须将其转换为 String。我还在回答中添加了一种更简洁的方式,as! String 可能会在转换失败时使您的应用崩溃,而 as? String 将允许转换失败
    • 太棒了!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2015-09-06
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多