2016-11-30 60 views
-1

我是使用XCode和Swift的新手,所以我想知道如何移动UILabel。这里是我的代码:如何通过录制其他UIButton来移动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

使用自动版式,只需设置自己的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,如果可能的话(包括IB和代码)都可以学习并坚持使用AutoLayout。学习可能令人望而生畏,但它使设备独立得多。
  • 在代码中使用AutoLayout时,请记得始终设置您的视图以将它们的转换为自动化超大小写入限制设置为false。这是每个人(包括我)所犯的最常见的错误之一。
  • 如果您将IB用于AutoLayout,则可以像设置视图一样设置IBOutlets的约束。
  • 有几种编码约束的方法。一个是上面的(使用是* Active),但另一个是设置约束数组,可以批量激活和取消激活。
0

试试这个...

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

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

    })