繁体   English   中英

xcode swift:如何拖动按钮?

[英]xcode swift: how to drag a button?

我正在使用xcode创建一个允许用户拖动按钮的视图。 使用下面的代码,我可以将按钮移到触摸处并从那里拖动,但是我不能单击按钮并拖动。

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {

    for obj in touches {
        let touch = obj as! UITouch
        let location = touch.locationInView(self.view)
        word1Button.center = location
    }

}

按钮会响应触摸事件,因此,当用户在按钮范围内向下触摸时,其下方的视图将不会收到这些触摸事件。 您可以通过在按钮上使用手势识别器来解决此问题,而不是依赖于较低级别的触摸传递方法。 长按手势识别器可能最有效:

// Where you create your button:
let longPress = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
word1Button.addGestureRecognizer(longPress)

//...

func handleLongPress(longPress: UILongPressGestureRecognizer) {
    switch longPress.state {
    case .Changed:
        let point = longPress.locationInView(view)
        button.center = point
    default:
        break
    }
}

请注意,默认情况下, UILongPressGestureRecognizer需要用户按住0.5秒,然后手势才能开始识别(并因此开始拖动)。 您可以使用minimumPressDuration属性更改此UILongPressGestureRecognizer 但是请注意不要使其太短-手势识别到该手势后,它将取消对按钮的其他触摸,以防止在抬起触摸时触发按钮动作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM