You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode9.2中,IB设置命名颜色后无法通过代码修改UIView背景颜色?

Issue with Named Colors Overriding Programmatic Background Color in Xcode 9.2

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(_:) or viewDidLayoutSubviews. Just note that viewDidLayoutSubviews can 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 to nil before 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:01:32