ios - How to customize uibutton's class in Swift? -
i have different types of buttons in app, , have way don't have write code format attributed labels or setup insets , background image in interface builder each button on every view controller.
i thinking of doing this:
import uikit class whitebutton: uibutton { required init(coder adecoder: nscoder) { super.init(coder: adecoder) if traitcollection.horizontalsizeclass == uiuserinterfacesizeclass.regular { contentedgeinsets.top = 16 contentedgeinsets.right = 47 contentedgeinsets.bottom = 16 contentedgeinsets.left = 47 } else { contentedgeinsets.top = 11 contentedgeinsets.right = 35 contentedgeinsets.bottom = 11 contentedgeinsets.left = 35 } let imageinsets : uiedgeinsets = uiedgeinsetsmake(4, 4, 4, 4) var image = uiimage(named: "white-button.png") image = image!.resizableimagewithcapinsets(imageinsets) setbackgroundimage(image, forstate: .normal) var formattedstring = nsmutableattributedstring(string: attributedtitleforstate(.normal)!.string) let fontdescriptor = uifontdescriptor(fontattributes: [uifontdescriptornameattribute : "avenirnext-bold"]) var font : uifont if traitcollection.horizontalsizeclass == uiuserinterfacesizeclass.regular { font = uifont(descriptor: fontdescriptor, size: 18) } else { font = uifont(descriptor: fontdescriptor, size: 12) } let attributes = [nsfontattributename : font] formattedstring.addattributes(attributes, range: nsmakerange(0, formattedstring.length)) formattedstring.addattribute(nskernattributename, value: 1.5, range: nsmakerange(0, formattedstring.length)) formattedstring.addattribute(nsforegroundcolorattributename, value: uicolor.whitecolor(), range: nsmakerange(0, formattedstring.length)) setattributedtitle(formattedstring, forstate: .normal) } }
this sort of works, have following questions:
- is way of doing it? have maybe 3 different types of buttons, i'd have subclass each one.
- the use of
traitcollection
determine size class not working. how fix (i tried accessing superview obtain it, nil)? want able give different font size, , insets, based on size class.
the best way make generic button class different colored buttons. after init new button, can set color.
another way use designated initialiser uicolor
code adapts color feed (init(color:uicolor)
).
you can access trait collection in didmovetosuperview
.
Comments
Post a Comment