【发布时间】:2017-01-02 15:50:31
【问题描述】:
在我的代码中,我希望 UIButton 从屏幕中心开始,然后单击它后,我希望它移动到屏幕上的随机位置。所以我把它的代码放在我点击它之后去一个随机位置,虽然问题是它是从一个随机位置开始而不是从中心开始。这是我的 ViewController.swift 的代码:
class ViewController: UIViewController {
@IBOutlet weak var btn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
btn.layer.cornerRadius = 10
btn.layer.position = CGPoint(x: self.view.center.x, y: self.view.center.y)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tapRandomBTN(_ sender: Any) {
let buttonWidth = btn.frame.width
let buttonHeight = btn.frame.height
// Find the width and height of the enclosing view
let viewWidth = btn.superview!.bounds.width
let viewHeight = btn.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.
btn.center.x = xoffset + buttonWidth / 2
btn.center.y = yoffset + buttonHeight / 2
}
}
【问题讨论】:
-
viewDidLoad中没有布局信息,因此与框架、位置、位置、中心...相关的所有内容都没有设置/定义/随机。试试viewDidLayoutSubviews例如