ios - Keep aspect ratio for UIbuttons background image -


i've been looking hours , find old answers saying cannot done.

i have button i'd background image large can be, while keeping aspect ratio. background image keeps getting streched no matter do. i've tried.

    var bluecircle = #imageliteral(resourcename: "blue.png")      monbreak.contentmode = uiviewcontentmode.scaleaspectfit     monbreak.setbackgroundimage(bluecircle, for: uicontrolstate.normal) 

do need make imageview , put invisible button on it? seems welcoming lot of new things go wrong.

i tried

@iboutlet weak var monbreak: uibutton!  override func viewdidload() {     super.viewdidload()      var bluecircle = #imageliteral(resourcename: "blue.png")      let theimagebehindmonbreak = uiimageview(image: bluecircle)     theimagebehindmonbreak.frame = cgrectfromstring( "{{0,0},{40,40}}")     monbreak.contentmode = uiviewcontentmode.scaleaspectfit     monbreak.addsubview(theimagebehindmonbreak)     theimagebehindmonbreak.image=bluecircle     theimagebehindmonbreak.contentmode = uiviewcontentmode.scaleaspectfit 

this gets aspect ratio right, since want layout dynamic setting size fixed values won't work, plus it's not centered.

at first tired applying constraints of button so

    var dacontraints = nslayoutconstraint(monbreak.constraints) 

but @ point error "cannot invoke initializer type 'nslayoutconstraint' argument list of type '{[nslayoutconstraints]}'

this killing me

sounds solution subclassing fits.

subclass uibutton, add imageview in init, size frame, , set contentmode properly.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -