R – Overload method (specifically drawRect:) without subclassing

overloadingsubclassinguiview

I'm using a container UIView to house a UIImageView and do some custom drawing. At this point I'd like to do some drawing on top of my subview. So overriding drawRect: in my container UIView will only draw below the subviews.

Is there a way to overload drawRect: in my subview without subclassing it?

I think method swizzling may be the answer, but I'm hoping not.

(NOTE: yes, it would have been smarter to have the UIView be the subview of the UIImageView, but unfortunately I'm committed to my mistake now.)

Best Answer

Are you sure you mean overload and not override?

Overloading -- creating a new method with the same basic name but different arguments and therefore a different selector -- could be accomplished by adding a new method category containing your new method to the existing class.

Overriding -- modifying the behavior of an existing method -- would require either monkey-patching the class's method table at runtime (for example, by swizzling) or subclassing.

Related Topic