ios - Using Autolayout Constraints programmatically to center a UIImageView inside a UIView Swift 2.3 iOS10 -
i have added uiview table cell through storyboard following constraints:
then have following code programmatically add uiimageview uiview above , size according orientation of screen.
//use half screen size width when on iphone , on landscape let image: uiimage = uiimage(named: header_image_bath)! imageview = uiimageview(image: image) imageview!.frame = cgrectmake(0 , 0, self.view.frame.width / 2, 185) imageview!.contentmode = .scaleaspectfit //center image let centerxconst = nslayoutconstraint(item: imageview!, attribute: .centerx, relatedby: .equal, toitem: imagewrapperview, attribute: .centerx, multiplier: 1, constant: 1) let centeryconst = nslayoutconstraint(item: imageview!, attribute: .centery, relatedby: .equal, toitem: imagewrapperview, attribute: .centery, multiplier: 1, constant: 1) nslayoutconstraint.activateconstraints([centerxconst, centeryconst]) //add sub view imagewrapperview.addsubview(imageview!)
however, image not centered when in landscape. image half width of screen , center inside uiview. missing? thanks
- you should use auto layout instead of frame width , height of imageview
- you have add imageview imagewrapperview before add constraints
- you have set imageview.translatesautoresizingmaskintoconstraints false
then, final code is:
//use half screen size width when on iphone , on landscape let image: uiimage = uiimage(named: "key.png")! let imageview = uiimageview(image: image) imageview.contentmode = .scaleaspectfit imageview.translatesautoresizingmaskintoconstraints = false //add sub view imagewrapperview.addsubview(imageview) //center image let centerxconst = nslayoutconstraint(item: imageview, attribute: .centerx, relatedby: .equal, toitem: imagewrapperview, attribute: .centerx, multiplier: 1.0, constant: 0.0) let centeryconst = nslayoutconstraint(item: imageview, attribute: .centery, relatedby: .equal, toitem: imagewrapperview, attribute: .centery, multiplier: 1.0, constant: 0.0) let heightconstraint = nslayoutconstraint(item: imageview, attribute: .height, relatedby: .equal, toitem: nil, attribute: .notanattribute, multiplier: 1.0, constant: 185.0) let widthconstraint = nslayoutconstraint(item: imageview, attribute: .width, relatedby: .equal, toitem: nil, attribute: .notanattribute, multiplier: 1.0, constant: self.view.frame.width / 2) imageview.addconstraints([heightconstraint, widthconstraint]) nslayoutconstraint.activateconstraints([centerxconst, centeryconst])
Comments
Post a Comment