求助:UISegmentedControl返回关闭控制器后重开 tintColor消失
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
headerSegmentitself (e.g., inviewWillDisappear: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

