带手势的IOS8和Swift多个视图不起作用

时间:2015-01-03 17:16:07

标签: ios swift ios8 gestures

我正在尝试基于泛型类构建用户界面,这些泛型类基于UIViewController类的相同扩展。这个例子在屏幕上放置方块,而tap事件将在父类中处理,但它不起作用。我做错了什么?

主ViewController.swift:

class ViewController : UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    //FIRST SQUARE
    let widget1 = TestWidget()
    widget1.viewX = 10
    widget1.viewY = 10
    self.view.addSubview(widget1.view)
    self.addChildViewController(widget1)
    widget1.didMoveToParentViewController(self)

    //SECOND SQUARE
    let widget2 = TestWidget()
    widget2.viewX = 100
    widget2.viewY = 100
    self.view.addSubview(widget2.view)
    self.addChildViewController(widget2)
    widget2.didMoveToParentViewController(self)
  }

}

这是TestWidget类:

class TestWidget : UIViewController {

  var viewX : CGFloat!

  var viewY : CGFloat!

  override func viewDidLoad() {
    super.viewDidLoad()
    let square = UIView()
    square.frame = CGRect(x : viewX, y : viewY, width: 50, height: 50)
    square.backgroundColor = UIColor.orangeColor()
    self.view.addSubview(square)
    //GESTURE PART
    var tapForSquare = UITapGestureRecognizer()
    tapForSquare.addTarget(self, action : "onTap")
    square.addGestureRecognizer(tapForSquare)
    square.userInteractionEnabled = true
    square.multipleTouchEnabled = true
  }

  func onTap() {
    println("square tapped")
  }
}

我在屏幕上有两个正方形,但点按动作仅适用于第二个。这有什么问题吗?

2 个答案:

答案 0 :(得分:0)

onTap()接受论证。它应该是:

onTap(gestureRecognizer: UITapGestureRecognizer)

并在此行中的“onTop”之后添加一个冒号:

tapForSquare.addTarget(self, action : "onTap")

答案 1 :(得分:0)

谢谢大家,有趣的是,只有在设置父视图框架时,这才有用。

类似于:

 override func viewDidLoad() {
    super.viewDidLoad()
    self.view.frame = CGRect(x : viewX, y : viewY, width: 50, height: 50)
    let square = UIView()
    square.frame = CGRect(x : 0, y : 0, width: 50, height: 50)
    square.backgroundColor = UIColor.orangeColor()
    self.view.addSubview(square)
    ...

}