objective-c - 快速的新手。如何创建或更新 View

标签 objective-c swift

在 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/

相关文章:

ios - 在 IOS 的 UITableView 中选择一个单元格时,表格单元格边框可见

objective-c - 如何忽略 "No visible @interface for X declares the selector"?

iphone - 我的应用程序在播放声音时崩溃

objective-c - 在 didSelectRow 上重新加载 UIPickerView

ios - 无法让平移手势工作

objective-c - 成员引用基类型 'void' 不是结构或 union (OBJ-C)

swift 4 : CUICatalog: Invalid asset name supplied: '(null)' when using AVPlayerViewController Only

ios - 将实例化的 UIView 从 NIB 约束到其他 UIView

ios - UISearchController 搜索栏没有获得焦点

swift - 在 Swift 中解析注册项目时出错