UITableView 在视图出现之前重置其背景颜色 [英] UITableView is resetting its background color before view appears

查看:24
本文介绍了UITableView 在视图出现之前重置其背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 UI 组件初始化方式可能有点奇特.我以编程方式创建它们,其中有一个 UITableView 实例,我在初始化时立即设置其背景颜色,如下所示:

I'm using probably a little bit exotic way of initialization of my UI components. I create them programmatically and among them is a UITableView instance, I set its background color immediately upon initialization, like this:

class MyViewController: UIViewController {
    ...
    let tableView = UITableView().tap {
         $0.backgroundColor = .black
         $0.separatorStyle = .none
    }
    ...
}

其中tap是扩展函数:

func tap(_ block: (Self) -> Void) -> Self {
    block(self)
    return self
}

这在我之前的项目中非常有效,该项目是在 Xcode 8 中创建的,然后迁移到 Xcode 9 而没有破坏任何东西.但是现在我在 Xcode 9 中创建了全新的项目并将上述扩展复制粘贴到它,但似乎出了点问题.当我的视图控制器出现在屏幕表上时,有白色背景和默认分隔符插入.

This worked very well in my previous project which was created in Xcode 8 and then migrated to Xcode 9 without breaking anything. But now I've created brand new project in Xcode 9 and copy-pasted above-mentioned extension to it, but seems like something went wrong. When my view controller appears on screen table has white background and default separator insets.

这似乎只影响了一些属性,因为其他属性都在正常工作(例如 $0.register(nib: UIINb?, forCellReuseIdentifier: String) 注册所需的单元类和 $0.showsVerticalScrollIndicator = false 隐藏滚动指示器.

This seems to affect only some of the properties because others are working as they should have (e.g. $0.register(nib: UINib?, forCellReuseIdentifier: String) registers required cell class and $0.showsVerticalScrollIndicator = false hides scroll indicator).

也许你们中的一些人可以让我知道事情的核心是什么.

Perhaps some of you, guys, could give me an idea what's the heart of the matter.

这是完整代码,要重现该问题,只需创建一个新项目并替换 ViewController.迅捷的内容.如您所见,table 具有正确的 rowHeight (160),但重置了其背景颜色.

Here's full code, to reproduce the issue simply create a new project and replace ViewController.swift's content. As you can see, table has correct rowHeight (160) but resets its background color.

至于视图出现之前"语句:我已经在 viewDidLoadviewWillAppearviewDidAppear 中打印了表格的背景颜色,如下所示:

As for "before view appears" statement: I've printed table's background color in viewDidLoad, viewWillAppear and viewDidAppear like this:

print(#function, table.backgroundColor.debugDescription)

——它只在最后一次调试打印中改变颜色:

– it changes its color only in the last debug print:

viewDidLoad() Optional(UIExtendedGrayColorSpace 0 1)
viewWillAppear Optional(UIExtendedGrayColorSpace 0 1)
viewDidAppear Optional(UIExtendedSRGBColorSpace 1 1 1 1)

推荐答案

我最终将初始化转移到了惰性 var 的函数中 - 结果发现在其视图控制器的初始化期间初始化 UITableView 有一些副作用.

I ended up moving the initialization to lazy var's function – turns out initializing UITableView during the initialization of it's view controller has some side effects.

这篇关于UITableView 在视图出现之前重置其背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆