如何通过录制其他UIButton来移动UILabel?

时间:2016-11-30 18:29:42

标签: ios swift uibutton uilabel

我在使用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,按下)。有什么想法吗?

2 个答案:

答案 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() }
}

注意:

  • 最后一行代码有助于为事物添加动画。
  • 长期,除非你绝对需要使用框架和CGRects,否则我们学习并在可能的情况下坚持使用AutoLayout(在IB和代码中)。学习它可能令人生畏,但它可以使设备更加独立。
  • 在代码中使用AutoLayout时,请务必设置视图以将 translatesAutoresizingMaskIntoConstraints 设置为false。这是每个人(包括我)最常犯的错误之一。
  • 如果您使用IB进行AutoLayout,您可以设置IBOutlets用于约束,就像您可以查看一样。
  • 有几种方法可以编码约束。一个在上面(使用是* Active ),但另一个是设置约束数组,可以批量激活和停用。

答案 1 :(得分:0)

试试这个......

将标签和按钮定义为全局实例。

UIView.animateWithDuration(1.0,
    delay: 0.0,
    options: .CurveEaseInOut,
    animations: {
      shot.center = button.center
    },
    completion: { finished in

    })