How can a UIView get a callback when it is added to its supervisor?

Problem

I have subclassed UIView . After an object of this subclass is added to its supervisor, it must autonomously run some code. How can I connect to this event to run my code?

Why do i need it

The background of the selected segmented UISegmentedControl is usually difficult to style. The best solution I could find was to hack:

#import "SegmentedControlStyled.h" @implementation SegmentedControlStyled - (void) updateStyle { for (NSUInteger i = 0; i < [self.subviews count]; i++) { if ([[self.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && [[self.subviews objectAtIndex:i] isSelected]) { [[self.subviews objectAtIndex:i] setTintColor:[UIColor colorWithWhite:0.7 alpha:1.0]]; } if ([[self.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && ![[self.subviews objectAtIndex:i] isSelected]) { [[self.subviews objectAtIndex:i] setTintColor:[UIColor colorWithWhite:0.9 alpha:1.0]]; } } } @end 

This updateStyle function must be called in two places. Obviously, the first is every time the user selects another segment. I can do this autonomously by overriding my SegmentedControlStyled addTarget function and SegmentedControlStyled addTarget event. The second place updateStyle needs to be called, after adding SegmentedControlStyled to its supervisor. You may ask: "Why do you call it, and not somewhere like init ?". Well, from my observations, calling it before it is attached to the hiearchy kind has no effect. Therefore, you need to write your code as follows:

 SegmentedControlStyled* seg = [[SegmentedControlStyled alloc] initWithItems:[NSArray arrayWithObjects:@"One", @"Two", nil]]; [self.view addSubview:seg]; [seg updateStyle]; 

The last line is ugly, because the employee who uses my subclass needs to understand why the view is broken, and he needs to know when to call updateStyle . To support the object-oriented principle of encapsulation , this detail should be transferred to the class itself. If I had the opportunity to detect when a view was added to its supervisor, I could encapsulate the hack style in my subclass.

+6
source share
2 answers

override any of

 - (void)didAddSubview:(UIView *)subview - (void)willMoveToSuperview:(UIView *)newSuperview - (void)willMoveToWindow:(UIWindow *)newWindow 

as needed?

+9
source

The selected state of the UISegmentedControl is not complicated.

You use the setBackgroundImage:forState:barMetrics: and use UIControlStateSelected as an argument to the forState: named parameter.

Everything you refer to in the subtitles of UIKit controls is a bad thing. You should not rely on internal implementation details.

0
source

Source: https://habr.com/ru/post/950018/


All Articles