ios - Swift: How to make a label in the borders of the screen? -


i'm trying create game generates labels randomly on screen, entire word must inside screen. have textfield in screen i'm intending put words beneath.

i have function adding label, , making sure it's inside borders.

func addword(word: string) {     let screensize: cgrect = uiscreen.mainscreen().bounds     let screenwidth = uint32(screensize.width)     let screenheight = uint32(screensize.height)     let label = uilabel()     label.text = word     label.font = uifont.systemfontofsize(32)     label.sizetofit()     label.backgroundcolor = uicolor.whitecolor()      let x = cgfloat(arc4random_uniform(screenwidth))     let y = cgfloat(arc4random_uniform(screenheight))      label.center = cgpointmake(x, y)     label.center = checkbounds(label, minx: 0, maxx: cgfloat(screenwidth), miny: (newwordstextfield.bounds.origin.y+newwordstextfield.bounds.maxy), maxy: cgfloat(screenheight))     view.addsubview(label)      let pangesture = uipangesturerecognizer(target: self, action: #selector(viewcontroller.handlepangesture(_:)))     label.addgesturerecognizer(pangesture)     label.userinteractionenabled = true }  func checkbounds(label: uilabel, minx: cgfloat, maxx: cgfloat, miny: cgfloat, maxy: cgfloat)->cgpoint{     let borders = label.bounds     var newcenter = label.center     if borders.minx < minx {         newcenter.x = newcenter.x + (minx-borders.minx)     }     if borders.maxx > maxx {         newcenter.x = newcenter.x-(borders.maxx-maxx)     }     if borders.miny < miny {         newcenter.y = newcenter.y + (miny-borders.miny)     }     if borders.maxy > maxy {         newcenter.y = newcenter.y-(borders.maxy-maxy)     }     return newcenter } 

but reason labels keep getting out of boundaries though function should've made sure wouldn't happen. i'm kind of new swift , it's first time i'm trying this, please, doing wrong?

if you're using auto layout (you because it's default , have turn off manually) frame , center of view objects gets overridden auto layout constraints (either once define or ones system creates automatically.)

if you're going add views manually need add constraints well. should fix problem. suggest googling "add uiviews , constraints through code" or similar find tutorials on how it's done (or better yet add views in storyboard , mark them hidden until need them.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -