私のコードでは、UIButtonを画面の中央で開始したいのですが、クリックした後、画面上の位置。だから私はそれをクリックした後にランダムな位置に移動するようにコードを書いていますが、問題は中心から始まるのではなくランダムな位置から始まっているということです。ここに私のViewController.swiftのコードは次のとおりです。あなたがストーリーボードにUIbuttonを持っているよう私のUIButtonは、中央で開始するのではなくランダムな位置から開始しています
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
}
}
そこにはレイアウト情報は、位置をフレームに関連するすべてのものは、したがって、存在しない場所、中心、...ランダム/定義/設定されていません。例えば 'viewDidLayoutSubviews'を試してください。 – luk2302