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:
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.
Pwner source share