I am building a 3rd party library that I plan to integrate on different projects, so I need this to be as modular and have a non-destructive nature as possible. I need to "hook on" frame changes of UIView
s. I am building a category and from that category method, I need to hook on that view's (it can be any regular UIView
or subclass) frame change, and perform my additional logic. I've looked at KVO but as seen here https://stackoverflow.com/a/19701380/811405 it's not a safe approach.
How can I hook on frame change of a UIView
? I can override setFrame:
in my category, but I know that it is the single worst thing an Objective-C programmer can make: overriding a default method in a category. How do I achieve this?
UPDATE: I'm currently working on a really ugly (but working) solution:
- I've created an invisible (empty
drawRect:
)UIView
subclass. - I'm instantiating and adding it to the view of which I want to be notified of frame changes.
- I'm setting that view's (the "superview") autoresizesSubviews to
YES
. - I'm setting my "invisible" view's autoresizing mask to both flexible width and height.
- I'm overriding my "invisible" view's
setFrame:
to notify the appropriate object via delegation.
Because the superview will set frame of all subviews with flexible autoresizing mask when autoresizesSubviews is YES, this works, but it involves adding a hidden view inside a view, which is a bit hacky and may create problems in some scenarios (though most are corner cases). I'm still searching for a more suitable/less hacky solution.