简体   繁体   中英

xcode swift: how to drag a button?

I am working with xcode to create a view that allows users to drag buttons. with the code below, I can move the button to the touch and drag from there, but I cant click the button and drag.

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
    }

}

Buttons respond to touch events, so when the user touches down within the bounds of a button the view underneath will not receive those touch events. You can get around this by using a gesture recogniser on your button instead of relying on the lower level touch delivery methods. A long press gesture recognizer would probably work best:

// 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
    }
}

Note that by default, the UILongPressGestureRecognizer needs the user to hold down for 0.5 seconds before the gesture starts recognizing (and therefore starts dragging). You can change this with the minimumPressDuration property of UILongPressGestureRecognizer . Be careful not to make it too short though - as soon as the gesture recognizes it will cancel other touches to the button, preventing the button action from being fired when the touch is lifted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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