ios - Best place to set cornerRadius based on UIButton size in subclass? -
so having few different rounded buttons within app (all way circular buttons), , can tell, easiest way achieve set cornerradius property of buttons calayer.
however, don't want doing manually every button requires in every controller, thought simple subclass sets on init way.
i using storyboard , autolayout position , size buttons, , assigning them subclass.
class roundedbutton: uibutton { required init(coder adecoder: nscoder) { super.init(coder: adecoder) self.layer.cornerradius = self.bounds.size.height / 2.0 self.clipstobounds = true nslog("button bounds: h-%f w-%f", self.bounds.size.height, self.bounds.size.width) nslog("button frame: h-%f w-%f", self.frame.height, self.frame.width) } }
but have come find out @ point (i.e. init), size of neither frame nor bounds final. button in storyboard sized (and constrained) h40 x w40, bounds/frame sizes showing h30 x w38.
this means cornerradius doesn't value expect.
i have confirmed @ later point (e.g. when button can respond tap) frame/bounds indeed h40 x w40.
so after that, question is, within uibutton subclass, when/where can safely set cornerradius using final frame/bounds values of instance?
if want code executed after view has gone through autolayout must in layoutsubviews
after calling super.layoutsubviews()
.
like :
class roundedbutton: uibutton { override func layoutsubviews() { super.layoutsubviews() layer.cornerradius = bounds.size.height / 2.0 clipstobounds = true } }
this code not perfect though because doesn't support when height bigger width (easy fix though…).
Comments
Post a Comment