ios - How to make reusable UIView template consisiting UILabels -
i'm building weather app beginner project. wanted custom view consisted on many uilabels temp, humidity, precipitation, etc. thought custom uiview used several times every city user has saved. if user has 3 cities saved, custom view have 3 instances.
what best way this? i'm trying subclass uiview. overriding drawrect(rect: cgrect) , defining uilabels there. didn't sense right. , wouldn't alloc/inited until way later, after trying update label text in completion handler on nsurlsession.
or should overriding init() makes me this:
required init(coder adecoder: nscoder) { fatalerror("init(coder:) has not been implemented") } and have no thought means. i'm forced doing when seek init frame on root vc.
override init(frame: cgrect) { super.init(frame: frame) } can walk me through best approach? have below nil value right when i'm trying add together uilabels subview of custom class.
class viewtemplate: uiview { var templabel: uilabel! var humiditylabel: uilabel! override init () { templabel = uilabel() templabel.frame = cgrectmake(halfscreenwidth - 130, 120, 260, 130) templabel.textcolor = uicolor.whitecolor() templabel.backgroundcolor = uicolor.clearcolor() // similar stuff humiditylabel super.init() addsubview(templabel) } override init(frame: cgrect) { super.init(frame: frame) } required init(coder adecoder: nscoder) { fatalerror("init(coder:) has not been implemented") } } if not quite sure nil coming from. importantly, i'm looking best practice in doing this. thanks!
you're on right track.
declare properties labels. looks you've done that. personally, declare constantslet instead of var because should have labels. override init(frame: cgrect) method. again, looks you've started this. reason should override init(frame: cgrect) instead if init() because init() calls init(frame: cgrectzero). if implement init() of properties may not initialized (although way less of issue swift since can declare properties constants compiler throws error). in initializer you're going want init labels & set them right before phone call super.init(frame). after super.init(frame) method called should add together labels subviews of self. override layoutsubviews() if laying ui out programmatically. method sizing , laying out of subviews. way it's i'm familiar with. if you're using autolayout believe it's best practice apply constraints in class's initializer since should ever need set once. optionally, may want override sizethatfits(). ensure view proper size when sizetofit() called on it. this goes not uiview subclass of it.
ios objective-c iphone uiview swift
No comments:
Post a Comment