我试图将标签移动到一个随机位置,我已经可以使用此代码执行此操作。
let buttonWidth = self.samea.frame.width
let buttonHeight = self.samea.frame.height
// Find the width and height of the enclosing view
let viewWidth = self.samea.superview!.bounds.width
let viewHeight = self.samea.superview!.bounds.height
// Compute width and height of the area to contain the button's center
let xwidth = viewWidth - buttonWidth
let yheight = viewHeight - buttonHeight
// Generate a random x and y offset
let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
// Offset the button's center by the random offsets.
self.newButtonX = xoffset + buttonWidth/2
self.newButtonY = yoffset + buttonHeight/2
self.samea.center.x = self.newButtonX!
self.samea.center.y = self.newButtonY!
问题是,我在故事板上有一些按钮和标签,我不希望按钮在这些按钮上生成。不知道该怎么做。任何帮助表示赞赏!
答案 0 :(得分:2)
您可以创建所有UIButton
和UILabel
出口的数组属性,并在viewDidLoad(_:)
方法中填充它。然后,当您生成随机值时,可以将它们放在while循环中并循环显示值。
像这样。
let buttonsAndLabels = [UIView]()
var xoffset: CGFloat
var yoffset: CGFloat
var isOccupied = true
while isOccupied {
xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
let frame = CGRect(x: xoffset, y: yoffset, width: buttonWidth, height: buttonHeight)
isOccupied = false
for view in buttonsAndLabels {
if view.frame.intersects(frame) {
isOccupied = true
}
}
}