【发布时间】:2017-01-29 18:06:44
【问题描述】:
我不确定是否有人问过这个问题,但我没有找到解决方案。我在一个按钮上实现平移手势,但想法是:按钮固定在一个位置,当用户拖动它时,会创建一个按钮的副本并随着手势移动;原来的保留在其初始位置(因此视图中将有 2 个按钮)。当平移结束时,新按钮用于一些处理,然后它应该消失(原来的保持原样;所以整个过程可以重复)。目前我所拥有的如下:
private func addPanGesture() {
for btn in self.selectors { //selectors is a list of buttons which needs this gesture
let pan = UIPanGestureRecognizer(target: self, action:#selector(self.panDetected(_:)))
pan.minimumNumberOfTouches = 1
pan.maximumNumberOfTouches = 1
btn.addGesturerecognizer(pan)
}
}
@objc private func panDetected(_ panGesture: UIPanGestureRecognizer) {
var translation = panGesture.translation(in: view)
panGesture.setTranslation(CGPoint(x: 0, y: 0), in: view)
var newButton = UIButton()
if let initButton = panGesture.view as? UIButton {
print ("Button recognized!") // this msg is printed out
newButton.center = CGPoint(x: initButton.center.x + translation.x, y: initButton.center.y + translation.y)
newButton.setImage(UIImage(named: "somename"), for: .normal)
}
if panGesture.state == UIGestureRecognizerState.began {
self.view.addSubview(newButton)
}
if panGesture.state == UIGestureRecognizerState.ended {
//some other processing
}
if panGesture.state == UIGestureRecognizerState.changed {
self.view.addSubview(newButton)
}
// printed-out msgs show began, ended, changed states have all been reached
}
但新按钮并没有出现在我的视图中。我可以知道如何解决这个问题吗?
【问题讨论】:
标签: ios uibutton uipangesturerecognizer