新的迅速。如何创建或更新视图

时间:2019-04-21 00:10:52

标签: objective-c swift

在目标c中,在表视图或集合视图中,我经常使用这样的代码...

// first time for a reusable cell, set up a subview and add it
UILabel *label = (UILabel *)[cell viewWithTag:32];
if (!label) {
    label = [[UILabel alloc] initWithFrame:...];
    label.tag = 32;
    [cell addSubview:label];
    // other one-time config stuff for label
}
// on the first time and all subsequent times
label.text = // something specific to this row

现在,尝试在Swift中做同样的事情,我做不到...

var label = cell.viewWithTag(32) as! UILabel
if (label == nil) { <---- compiler error - can't compare non-optional to nil

似乎强制转换使标签成为非可选标签,编译器表示将非可选标签与nil进行比较没有意义。但是它仍然是可选的,不是吗?

如果不强制转换,我可以走得更远,但是类型检查会让我...

    var label = cell.viewWithTag(32)
    if (label == nil) {
        label = UILabel()
        label?.tag = 32
        label?.textAlignment = .center  <--- compiler error - UIView doesn't have textAlignment

如何快速完成此模式?

1 个答案:

答案 0 :(得分:1)

尝试一下:

var label = cell.viewWithTag(32) as? UILabel

问题是,当您使用as!时,您将强制解开viewWithTag(_:)返回的值,即UIView?。当执行强制拆包并且值为nil或要转换为不匹配的类型时,会出现运行时错误。否则,它就可以正常工作,并且由于您具有未包装的值,因此将其与nil进行比较是没有意义的。至于as?,这实际上是一种尝试。对于as!而言,它不会引发任何错误。

因此,第一次运行上面发布的代码时,您将获得一个UILabel?nil的代码。其他时候,它仍然是UILabel?,但是它将包装(非nil)UILabel

相关问题