0
我試圖創建一個遊戲,在屏幕上隨機生成標籤,但整個單詞必須在屏幕內。我在屏幕上還有一個文本框,我打算將文字放在下面。Swift:如何在屏幕邊界製作標籤?
我有添加標籤爲確保它的邊框內的一個功能,而另一個。
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
}
但由於某些原因,即使函數應該確保不會發生,標籤仍然越界。我很快就有點新,這是我第一次嘗試這樣的事情,請幫助,我做錯了什麼?