ios - Swift: How to implement User Defined Runtime Attributes -
so implementing custom "chooser" toolbar, ios equivalent of radio button set (uisegmentedcontrol
). horizontal bar divided options.
to this, created subclass of uicontrol
called segmentedcontrol
, implemented custom drawing. however, such view, need option set available options are. have accessed view controller's viewdidload()
, set there, using interface builder kind of stuff.
so discovered wonderful thing called "user defined runtime attributes." created string
attribute key buttonvalues
, set value (this simple male/female chooser went "male|female"). found out can access these values using function self.valueforkey()
, pass in key. made parser turn string array , added functionality drawrect()
function use array set buttons.
when ran app, got error "key value coding-compliance."
so looked up, , found out class has have backing variables store attributes. fine, added instance variable called buttonvalues
, initialized ""
. app runs fine value comes out empty self.valueforkey()
function. looked tutorials on how set user defined runtime attributes don't go enough detail. talk key value coding-compliance it's should know.
i know must work properly, in gory detail.
for purposes can use either user-defined runtime attributes or expose class , properties editable in interface builder. either way, you'll want declare properties implicitly unwrapped optional variables -- iboutlets
created same way. if need make other changes once properties have value, give them didset
property observers. properties @ default value during initialization (or nil
if no default set) , set when view added superview.
user defined runtime attributes
this works more or less you've described above -- here's simplest version:
class labeledview : uiview { var viewlabel: string! { didset { println("didset viewlabel, viewlabel = \(self.viewlabel)") } } init(coder adecoder: nscoder!) { super.init(coder: adecoder) println("init coder, viewlabel = \(self.viewlabel)") } }
then set viewlabel
attribute "hello" on view in storyboard, so:
when build & run, console show property being set correctly:
init coder, viewlabel = nil didset viewlabel, viewlabel = hello
@ibdesignable & @ibinspectable
this gives custom view nicer interface in ib -- set @ibdesignable
attribute on class , @ibinspectable
attributes on each property. here's same class:
@ibdesignable class labeledview : uiview { @ibinspectable var viewlabel: string! init(coder adecoder: nscoder!) { super.init(coder: adecoder) } }
now can set inspectable properties @ top of attributes inspector in interface builder:
Comments
Post a Comment