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

求助:UISegmentedControl返回关闭控制器后重开 tintColor消失

Fixing UISegmentedControl TintColor Disappearing on Re-opening View Controller

Hey there, let's troubleshoot why your UISegmentedControl's tintColor vanishes when you re-open the view controller—this is a super common UIKit quirk, and we can fix it easily!

Possible Causes

The issue typically happens because:

  • You're relying on inherited tintColor (from the parent view or global UI settings) instead of explicitly setting it. When the view controller is destroyed and recreated, that inherited state might not carry over correctly.
  • If your view controller is being cached/reused (e.g., in a navigation stack or tab bar), the segmented control's state isn't being reset when the view reappears.

Solutions

1. Explicitly Set the TintColor During Initialization

Instead of letting the segmented control inherit its tintColor, set it directly when you create the control. This ensures it always has a defined color, no matter how many times the view controller is opened.

Update your initialization code like this:

headerSegment = [[UISegmentedControl alloc] initWithItems:segmentItemsArray];
headerSegment.selectedSegmentIndex = 0;
headerSegment.apportionsSegmentWidthsByContent = YES;
headerSegment.layer.borderWidth = 0;
// Add this line to set your desired tint color
headerSegment.tintColor = [UIColor systemBlueColor]; // Replace with your custom color if needed

You can use any UIColor here—whether it's a system color or a custom one you define.

2. Reset TintColor in viewWillAppear:

If your view controller might be reused (for example, if you're keeping a reference to it instead of creating a new instance each time), add a check in viewWillAppear: to reapply the tintColor. This guarantees the color is set every time the view becomes visible:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // Re-set the tint color to ensure it's applied
    self.headerSegment.tintColor = [UIColor systemBlueColor];
}

3. Check for Accidental TintColor Overrides

Double-check if any other code in your project is modifying the tintColor of:

  • The headerSegment itself (e.g., in viewWillDisappear: or a button action)
  • The parent view, navigation controller, or key window (global tintColor changes affect inherited values)
    If you find any unintended modifications, remove or adjust them to avoid overriding your desired color.

Final Notes

By explicitly setting the tintColor instead of relying on inheritance, you eliminate the ambiguity that causes this issue. The viewWillAppear: step adds an extra safety net for reused view controllers.

内容的提问来源于stack exchange,提问作者Mayur Shinde

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:10:03