ios - Swift - Adding subviews to a UIImageView at the same position for all devices -


i have indoor mapping application. have .png represents map. pins need placed on map programmatically @ points of interest (stairs, elevators, shops etc).

let's on iphone 5, add uiview subview uiimageview @ point

cgpointmake(100,y:100) 

and indicates(is put over) stairs in uiimageview. problem is, when run app on ipad, example, uiimageview larger , uiview not on stairs. have modify x,y uiview.

i have tried make calculation determine newx , newy of uiview according

uiscreen.mainscreen().bounds.size.width 

and

uiscreen.mainscreen().bounds.size.height 

but couldn't manage place uiview in same spot every device.

is there 3rd party library can solve problem? or equation determine newx , newy?

thank you,

dragos

there 2 ways approach this: 1) manually 2) constraints.

1) manually set cgpoint in switch

you set cgpoint exact values based on screen size using following switch:

if uidevice().userinterfaceidiom == .phone {     switch uiscreen.mainscreen().nativebounds.height {         case 960:             // set cgpoint 4         case 1136:             // set cgpoint 5         case 1334:             // set cgpoint 6         case 2208:             // set cgpoint 6plus         default:             break     } } 

advantage of this: it's quick , easy. disadvantages: doesn't scale (pun intended) new potential screen sizes apple might release. doing isn't how apple intended developers create interfaces, brings me to...

2) use constraints dynamically calculate position

i'm not sure how view setup, can't tell constraints use. however, use mix of leading, trailing, top, bottom, centerx, , centery perfect position.

you can add constraints in storyboard (easier in opinion) or in swift this:

let pinview = uiview() pinview.translatesautoresizingmaskintoconstraints = false self.view.addsubview(pinview)  let horizontalconstraint = nslayoutconstraint(item: pinview, attribute: nslayoutattribute.centerx, relatedby: nslayoutrelation.equal, toitem: view, attribute: nslayoutattribute.centerx, multiplier: 1, constant: 0) view.addconstraint(horizontalconstraint)  let leadingconstraint = nslayoutconstraint(item: pinview, attribute: nslayoutattribute.leading, relatedby: nslayoutrelation.equal, toitem: view, attribute: nslayoutattribute.leadingmargin, multiplier: 1, constant: 0) view.addconstraint(leadingconstraint) 

the nice things constraints 1) how apple intended 2) scales 3) there's less manual calculating do.

for more information on constraints, i'd give these read:


Comments