我试图在一堆动态生成的UIViews中为swift app中的所有四个方向实现swipeGestureRecognizer。基本上,我希望每个视图都能响应所有四个方向的滑动。这是我的代码
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//create a view to represent the main box
let mainBox = UIView(frame: CGRectMake(0,0, 320, 40 ))
mainBox.backgroundColor = UIColor.redColor()
mainBox.layer.cornerRadius = 0
mainBox.layer.borderWidth=1
self.view.addSubview(mainBox) //Add the newly created view to the main view(self)
//Create some UIViews on the fly
for var i=0; i<8; ++i{
//Add an image view
let tile = UIImageView(frame: CGRectMake(CGFloat(i)*CGFloat(40),0,40,40 )) //Create a new view
//Style the imageview
tile.backgroundColor=UIColor.greenColor()
tile.layer.cornerRadius=2
tile.layer.borderWidth=1
tile.userInteractionEnabled = true
let swipeRight = UISwipeGestureRecognizer(target: self, action:Selector("tileRightSwiped:"))
swipeRight.direction = .Right
tile.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("tileLeftSwiped"))
swipeLeft.direction = .Left
tile.addGestureRecognizer(swipeLeft)
let swipeDown = UISwipeGestureRecognizer(target: self, action: Selector("tileDownSwiped"))
swipeDown.direction = .Down
tile.addGestureRecognizer(swipeDown)
let swipeUp = UISwipeGestureRecognizer(target: self, action: Selector("tileUpSwiped"))
swipeUp.direction = .Up
tile.addGestureRecognizer(swipeUp)
mainBox.addSubview(tile) //Add the newly created view to mainBox
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//swipe gestures
func tileRightSwiped(gestureRecognizer: UISwipeGestureRecognizer){
print("right swiped")
}
func tileLeftSwiped(gestureRecognizer: UISwipeGestureRecognizer){
print("left swiped ")
}
func tileDownSwiped(gestureRecognizer: UISwipeGestureRecognizer){
print("down swiped ")
}
func tileUpSwiped(gestureRecognizer: UISwipeGestureRecognizer){
print("Up swiped ")
}
}
右滑动工作正常,但我无法理解为什么其他3个方向,应用程序意外中止,我得到这样的错误 &#34; [myApp.ViewController tileDownSwiped]:无法识别的选择器发送到实例0x7fd230dbf5d0&#34;我错误地使用了swipegesture识别器,或者我的代码中的其他地方出了什么问题? 我完全失败了。非常感谢任何帮助。
答案 0 :(得分:2)
您添加到手势中的选择器是错误的,因为您错过了结尾的冒号。这就是你看到崩溃的原因。
您可能还需要向手势识别器添加代理并实施shouldRecognizeSimultaneouslyWithGestureRecognizer:
,以便它们可以同时工作。