objective c - Subclass UILabel and UITextView with common UIView -
i trying add gradient background of both uilabel , uitextview. draw gradient overriding drawrect method in each of subclasses , adding identical properties each of subclasses too. question how best simplify/combine code, since both drawrect method , additional properties identical.
it great if replace/subclass uiview both uilabel , uitextview inherit from. change drawrect code in common subclass , add new properties uiview subclass well. don't think possible (i love wrong). i've thought simplifying code in drawrect method of called via separate functions, contained in separate class, still leave properties.
any ideas?
after research found there solution allows add methods and instance variables (properties) existing framework class uiview
.
you'll need 2 things:
- a category. (apple docs: detailed description)
- associated objects. (good example)
a category enables add instance methods existing class cannot store instance variables i.e. properties. luckily there work-around this: can create so-called associated object (that stored externally) , manually declare getter , setter methods:
uiview+background.h
@interface uiview (background) @property (nonatomic, copy) uiview *yourproperty; @end
uiview+background.m
#import "uiview+background.h" nsstring *const propertykey = @"yourpropertykey"; @implementation uiview (background) - (void)setyourproperty:(uiview *)propertyvalue { objc_setassociatedobject(self, propertykey, propertyvalue, objc_association_copy); } - (uiview *)yourproperty { return objc_getassociatedobject(self, propertykey); } @end
i haven't tested yet should work.
Comments
Post a Comment