在 objective-c 中,在 TableView 或 Collection View 中,我经常使用这样的代码......
// 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
如何在 swift 中执行此模式?
最佳答案
试试这个:
var label = cell.viewWithTag(32) as? UILabel
问题是当你使用 as!
时,你会强制展开从 viewWithTag(_:)
返回的值,这是一个 UIView?
。当您执行强制展开并且值为 nil 或您要转换为不匹配的类型时,您会收到运行时错误。否则它工作得很好,并且因为你有一个未包装的值,所以没有必要将它与 nil 进行比较。至于as?
,这其实是一种尝试转换。它不会像 !
那样抛出任何错误。
因此,当您第一次运行我上面发布的代码时,您将得到一个 UILabel?
和 nil
。其他时候它仍然是 UILabel?
,但它会包装一个(非 nil)UILabel
。
关于objective-c - 快速的新手。如何创建或更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55778804/