2015-07-03 82 views

回答

0

這段代碼獲得的x座標的隨機數和y座標的隨機數,然後爲它們分配是UIImageView

let IMAGE_WIDTH = //whatever the width of your uiimageview is 
let IMAGE_HEIGHT = //whatever the height of your uiimageview is 

// calculate the size of the rectangle that the random point can be in 
let VALID_WIDTH = UIScreen.mainScreen().bounds.size.width - IMAGE_WIDTH 
let VALID_HEIGHT = UIScreen.mainScreen().bounds.size.height - IMAGE_HEIGHT 

let x = CGFloat(CGFloat(arc4random()) % VALID_WIDTH) 
let y = CGFloat(CGFloat(arc4random()) % VALID_HEIGHT) 

var myImageview = UIImageView() 
myImageView.frame = CGRectMake(x, y, IMAGE_WIDTH, IMAGE_HEIGHT) 

// add the imageview to the view you want to display it in 
coolView.addSubview(myImageview) 
+0

感謝很多的左上角的座標,但我已經遇到了一個問題關於運營商的類型,所以我試圖將int轉換爲cgfloat – marc

+0

謝謝。我改變了代碼以在其中進行類型轉換。我忘了'arc4random'和'CGFloat'之間的%。 – Aderis