2016-03-30 13 views
0

Ich habe eine UIView, die ich an einem zufälligen Ort innerhalb der Breite und Höhe des Geräts erscheinen soll. Ich möchte auch, dass der Y-Standort nicht unter 20 Punkten liegt. Hier ist, was ich getan habe, aber die UIView manchmal scheint aus dem Bildschirm oder teilweise aus dem Bildschirm:Swift: Randomize UIButton Position innerhalb Ansicht

superDab = SuperDabButton(frame:CGRectMake(CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.width)! - (superDabImage!.size.width)))), 
      (CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.height)! - (superDabImage!.size.height))))), 
      (superDabImage!.size.width), 
      (superDabImage!.size.height)), 
      time: 5.0) 
     self.view?.addSubview(superDab!) 

Bitte um Hilfe! Vielen Dank!

+0

Was bestimmt die Breite und Höhe der Schaltfläche? Wird die Größe nach dem init (frame :) geändert? –

+0

Die Breite und Höhe der Schaltfläche wird durch die Größe eines UIImage bestimmt. In diesem Fall war es superDabImage. Hat das deine Frage beantwortet? @DavidWong – OriginalAlchemist

+0

Ist dieses Bild festgelegt, um Grenzen zu begrenzen? –

Antwort

0

Got dies, indem Sie diese arbeiten und kann mit dem gleichen Konzept auf alles angewendet werden:

var xPos = CGFloat() 
var yPos = CGFloat() 

//Finds random CGFloat within the width and height 
xPos = (CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.width)!)))) 
yPos = (CGFloat(arc4random_uniform(UInt32((self.view?.frame.size.height)!)))) 

//If statements saying that if the x pos is larger than the width - the size of the button, 
then do modulus on it using the equation below 
if (xPos > ((self.view?.bounds.width)! - (self.view?.bounds.width)! * 0.20)){ 
    xPos = xPos % ((self.view?.bounds.width)! - (self.view?.bounds.width)! * 0.20)} 
if (yPos > ((self.view?.bounds.height)! - (self.view?.bounds.width)! * 0.20)){ 
    yPos = yPos % ((self.view?.bounds.height)! - (self.view?.bounds.width)! * 0.20)} 

//Note: I use the "- (self.view?.bounds.width)! * 0.20" for the ypos only because 
my button is a circle, so most likely others would use the height instead of width