创建移动的新按钮时,按钮停止移动

时间:2015-12-30 04:50:09

标签: ios swift uibutton swift2 cadisplaylink

我正在创建一个游戏,当我点击一个名为start的按钮时,正在创建的按钮从屏幕的一侧移动到另一侧。问题是,当我在移动的按钮到达其终点之前单击“开始”时,它会停止而不是继续(并且另一个创建的按钮开始按预期移动)。 每次单击开始按钮时,我应该创建一个新的CADisplayLink吗?如果是这样,我该怎么做?这是代码:

var button1 = UIButton()
var displayLink: CADisplayLink?
var startTime: CFAbsoluteTime?
let duration = 2.0
var leadingConstraint: NSLayoutConstraint!
var topConstraint: NSLayoutConstraint!
var l1 = false
@IBAction func start(sender: UIButton) {
    n1()
}
func n1() {
    l1 = false
    startTime = CFAbsoluteTimeGetCurrent()
    displayLink = CADisplayLink(target: self, selector: "handleDisplayLink:")
    displayLink?.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
func handleDisplayLink(displayLink: CADisplayLink) {
    if l1 == false { // so it doesn't randomize leading constraint twice
        button1 = createButton()
        let randomNumber = Int(arc4random_uniform(180) + 30)
        let elapsed = CFAbsoluteTimeGetCurrent() - startTime!
        var percentComplete = CGFloat(elapsed / duration)
        if percentComplete >= 1.0 {
            percentComplete = 1.0
            //   self.button1.removeFromSuperview()
            displayLink.invalidate()
            button1.hidden = true
        }
        leadingConstraint.constant = CGFloat(randomNumber)
        topConstraint.constant = 390 - 350 * percentComplete
        NSLayoutConstraint.activateConstraints([
            leadingConstraint,
            topConstraint,
            button1.widthAnchor.constraintEqualToConstant(75),
            button1.heightAnchor.constraintEqualToConstant(75)
            ])
        l1 = true
    }
    else{
        let elapsed = CFAbsoluteTimeGetCurrent() - startTime!
        var percentComplete = CGFloat(elapsed / duration)
        if percentComplete >= 1.0 {
            percentComplete = 1.0
            displayLink.invalidate()
            button1.hidden = true
        }
        topConstraint.constant = 390 - 350 * percentComplete
        NSLayoutConstraint.activateConstraints([
            leadingConstraint,
            topConstraint,
            button1.widthAnchor.constraintEqualToConstant(75),
            button1.heightAnchor.constraintEqualToConstant(75)
            ])
    }
}
func buttonPressed(sender: UIButton!) {
    button1.hidden = true
    displayLink?.invalidate()
}
func createButton() ->UIButton {
    let button = UIButton()
    button.setImage(UIImage(named: "BlueBall.png")!, forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(button)
    button.translatesAutoresizingMaskIntoConstraints = false
    leadingConstraint = button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 0)
    topConstraint = button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 0)
    NSLayoutConstraint.activateConstraints([
        leadingConstraint,
        topConstraint,
        button.widthAnchor.constraintEqualToConstant(75),
        button.heightAnchor.constraintEqualToConstant(75)
        ])
    return button
}

请帮忙。真的很感激。提前致谢。安东

1 个答案:

答案 0 :(得分:0)

好的Anton O;正如我所讨论的,我发布了一个如何检测移动UIView上的触摸的答案。这适用于CAAnimation和UIView.animationWith ..

首先我创建了一个扩展的CGRect ,只是为了方便起见:

extension CGRect {
    init(position: CGPoint, size: CGSize) {
        self.origin = CGPoint(x: position.x - (size.width / 2.0), y: position.y - (size.height / 2.0))
        self.size = size
    }
}

然后我创建了两个创建和移动视图的方法。您可以根据需要调整代码。 (我持有一个名为nextView的全局变量来保持对视图的引用,当然也可以扩展到数组)

创建视图:

private func createView(index: Int) {
        nextView?.removeFromSuperview()

        nextView = UIView()
        nextView?.bounds = CGRect(x: 0, y: 0, width: 60, height: 60)
        nextView?.backgroundColor = UIColor.redColor()
        nextView?.center = CGPoint(x: 30, y: CGRectGetMidY(self.view.bounds))

        if let nextView = nextView {
            view.addSubview(nextView)
        }
    }

移动视图

private func moveView() {
        guard let nextView = nextView else {
            return
        }

        UIView.animateWithDuration(5.0) { () -> Void in
            nextView.center = CGPoint(x: CGRectGetMaxX(self.view.bounds) + 30, y: CGRectGetMidY(self.view.bounds))
        }
    }

检测触摸:

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesEnded(touches, withEvent: event)

        if let touch = touches.first, nextView = nextView {
            let touchRect = CGRect(position: touch.locationInView(self.view), size: CGSize(width: 20, height: 20))

            guard let viewPosition = nextView.layer.presentationLayer()?.position else {
                return
            }

            let viewRect = CGRect(position: viewPosition, size: nextView.bounds.size)

            if CGRectIntersectsRect(touchRect, viewRect) {
                print(" ")
            } else {
                print("")
            }
        }
    }

您可以根据需要扩展方法,还可以添加一些“性能”增强检查(例如,如果视图可见并在touchesEnded方法中移动或返回,等等。)