我在使用XCode和Swift时非常新,所以我想知道如何移动UILabel。这是我的代码:
@IBAction func startButton(_ sender: UIButton) {
sender.isHidden = true
drawtarget()
}
var hosPos = Int(arc4random_uniform(253)) + 10
var verPos = 580
func drawtarget() {
let button = UIButton(frame: CGRect(x: hosPos, y: verPos, width: 47, height: 47))
button.backgroundColor = UIColor(red: 102/255, green: 205/255, blue: 255/255, alpha: 1.0)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.addTarget(self, action: #selector(foo(sender:)), for: .touchUpInside)
view.addSubview(button)
}
func creatingShot(_ sender: UILabel) {
let shot = UILabel(frame: CGRect(x: 217, y: 50, width: 8, height: 8))
shot.backgroundColor = UIColor.green
shot.text = ""
view.addSubview(shot)
}
func foo(sender: UIButton) {
sender.isHidden = true
perform(#selector(drawtarget), with: nil, afterDelay: 3.0)
hosPos = Int(arc4random_uniform(253)) + 10
verPos = 600
}
所以,我需要将镜头(UILabel)移动到按钮的中心(UIButton,按下)。有什么想法吗?
答案 0 :(得分:0)
使用AutoLayout,只需将它们的centerAnchors设置为彼此相等:
@IBOutlet weak var myLabel:UILabel!
@IBOutlet weak var myButton:UIButton!
@IBAction func moveLabelToMe(sender: UIButton) {
myLabel.centerXAnchor.constraint(equalTo: myButton.centerXAnchor).isActive = true
myLabel.centerYAnchor.constraint(equalTo: myButton.centerYAnchor).isActive = true
UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() }
}
注意:
答案 1 :(得分:0)
试试这个......
将标签和按钮定义为全局实例。
UIView.animateWithDuration(1.0,
delay: 0.0,
options: .CurveEaseInOut,
animations: {
shot.center = button.center
},
completion: { finished in
})