ios - How to center view with dynamic height using auto layout -
i'm trying programmatically create view centered inside designated superview. can achieve behavior, centered view not respect dynamic height of content. here function created make happen:
static func overlaywithbutton(onview view: uiview, buttontext: string, theme: theme = .dark, action: action? = nil) -> uiview { // create overlay let overlay = uiview() overlay.translatesautoresizingmaskintoconstraints = false let leftinset: cgfloat = 20 let rightinset: cgfloat = 20 // style overlay overlay.backgroundcolor = theme == .dark ? uicolor.black : uicolor.white overlay.alpha = 0.75 overlay.cornerradius = 10 // create button let button = uibutton(frame: cgrect(x: 0, y: 0, width: 100, height: 100)) button.translatesautoresizingmaskintoconstraints = false // style button button.backgroundcolor = uicolor.clear button.settitle(buttontext, for: .normal) button.settitlecolor(theme == .dark ? lightbluebuttontext : uicolor.black, for: .normal) button.titlelabel?.linebreakmode = .bywordwrapping button.titlelabel?.textalignment = .center button.titlelabel?.numberoflines = 0 button.titlelabel?.font = uifont.boldsystemfont(ofsize: 20) button.isenabled = true // add button action if let action = action { button.add(for: .touchupinside, action) } // add constraints overlay.addsubview(button) button.centerxanchor.constraint(equalto: overlay.centerxanchor).isactive = true button.leftanchor.constraint(greaterthanorequalto: overlay.leftanchor).isactive = true button.rightanchor.constraint(lessthanorequalto: overlay.rightanchor).isactive = true button.topanchor.constraint(equalto: overlay.topanchor).isactive = true button.bottomanchor.constraint(equalto: overlay.bottomanchor).isactive = true view.addsubview(overlay) overlay.leftanchor.constraint(equalto: view.leftanchor, constant: leftinset).isactive = true overlay.rightanchor.constraint(equalto: view.rightanchor, constant: -rightinset).isactive = true overlay.centeryanchor.constraint(equalto: view.centeryanchor).isactive = true return overlay }
this works short button titles: however, longer title, button content clipped: using reveal can see title / button label responding intended. i've been @ quite while now, , can't centered overlay expand height match intrinsic content size of contents. ideas?
for view want center use these 2 lines:
view.center.x = self.view.center.x view.center.y = self.view.center.y
Comments
Post a Comment