Xcode9.2中,IB设置命名颜色后无法通过代码修改UIView背景颜色?
Yep, you’re far from the only developer who’s run into this frustrating quirk in Xcode 9.2! Let’s break down what’s happening and how to fix it.
What’s Going On?
When you set a view’s background color to a named color from the asset catalog via Interface Builder, Xcode 9.2 has a known timing issue: the system re-applies the IB-set color after viewDidLoad runs. That means your line of code:
view.backgroundColor = .red // 无效,IB中设置的资源颜色仍保留
gets overwritten by the named color from your asset catalog later in the view controller lifecycle (usually in viewWillLayoutSubviews or similar).
Is this normal behavior? Short answer: No, this is a bug specific to Xcode 9.x. Later versions of Xcode (10 and above) fixed this lifecycle timing mismatch, so the issue doesn’t occur there.
Fixes to Try
Here are a few reliable workarounds:
- Move your code to a later lifecycle method: Place the background color assignment in
viewWillAppear(_:)orviewDidLayoutSubviews. Just note thatviewDidLayoutSubviewscan be called multiple times (e.g., when the view resizes), so you might want to add a check to avoid redundant changes:override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if view.backgroundColor != .red { view.backgroundColor = .red } } - Reset the color first in
viewDidLoad: Explicitly set the background color tonilbefore assigning your desired color. This breaks the IB color’s persistence:override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = nil view.backgroundColor = .red } - Upgrade Xcode: If possible, moving to Xcode 10 or newer eliminates the issue entirely, as Apple fixed this timing bug in those releases.
内容的提问来源于stack exchange,提问作者Joris Weimar

