0

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 UIViews. 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.

Community
  • 1
  • 1
Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
  • Have you looked at KVO? – CrimsonChris Nov 29 '14 at 21:01
  • @CrimsonChris according to this answer: http://stackoverflow.com/a/19701380/811405 it's not a safe approach. it does seem to work according to another answer, but it relies on undocumented behavior which would be subject to change, and I don't want to build a framework/library utilizing undocumented behavior. – Can Poyrazoğlu Nov 29 '14 at 21:13
  • Is subclassing your views an option? You could provide your own way to hook into frame changes that way. – CrimsonChris Nov 29 '14 at 22:43
  • Swizzling might be another option. – CrimsonChris Nov 29 '14 at 22:44
  • @CrimsonChris unfortunatelly not. I want my library to be modular and compatible with regular UIViews and be easily integratable. I'm currently working on an "ugly way". See my updated question. – Can Poyrazoğlu Nov 29 '14 at 22:49
  • Both KVO and method swizzling can accomplish what you seek. They both have dangers. Either approach will likely be cleaner than the approach you are taking now. – CrimsonChris Nov 29 '14 at 22:54

0 Answers0