【发布时间】:2016-06-27 23:51:08
【问题描述】:
我的 UI 中有 3 个按钮,它们的最终表现类似于钢琴上的琴键。 3 个按钮中的任何一个都可以被点击以执行特定按钮的操作,但用户可以将手指“滑动”到下一个按钮上以执行按钮 2 的操作。
我进行了一些搜索,看起来 touchesBegan 方法检测水龙头的位置是最好的。我的尝试如下:
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
(我没有与 3 个按钮相关联的任何操作事件,因为我认为 touchesBegan 会涵盖这一点。)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
var touch: UITouch = event!.allTouches()!.first!
var location: CGPoint = touch.locationInView(touch.view!)
if CGRectContainsPoint(button1.frame, location){
print("button 1")
}
else if CGRectContainsPoint(button2.frame, location) {
print("button 2")
}
else if CGRectContainsPoint(button3.frame, location) {
print("button 3")
}
}
当我测试这个时,没有任何东西打印到控制台。我测试了点击和滑动按钮。我应该使用 UIViews 而不是 UIButtons 吗?我应该在按钮上使用操作吗?这适用于 Swift 2.0。谢谢。
编辑
我有一个工作原型更接近于我对这个功能的设想。这个线程在这里:Using iOS pan gesture to highlight buttons in grid 向我指出了在按钮超级视图上使用 pangesture 的方向。
var touchPoint = CGPoint()
var myGesture = UIPanGestureRecognizer()
viewDidLoad:
myGesture = UIPanGestureRecognizer(target: self, action: Selector("panDetected:"))
myGesture.maximumNumberOfTouches = 1
view.addGestureRecognizer(myGesture)
.
func panDetected(sender : UIPanGestureRecognizer) {
touchPoint = sender.locationInView(self.view)
if CGRectContainsPoint(button1.frame, touchPoint) {
button1Func()
}
else if CGRectContainsPoint(button2.frame, touchPoint) {
button2Func()
}
else if CGRectContainsPoint(button3.frame, touchPoint) {
button3Func()
}
上面的操作确实有效,但是 button1Func / button2Func / button3Func 都包含一个动画块。当手指在按钮内拖动时,每次检测到移动时都会触发该方法。我只需要这种情况发生一次。我尝试将它添加到 state == .Began 语句中,但是一旦手指离开第一个被点击的按钮,就会阻止任何功能。
一旦手指位于 3 个按钮的边界内,我有什么方法可以在平移手势内触发这些方法(button1Func / button2Func / button3Func)一次?如果令人困惑,我将很乐意澄清这一点。谢谢。
【问题讨论】: