添加到UIView的子视图时无法识别UISwipeGestureRecognizer

时间:2016-06-05 22:21:50

标签: swift uiview

我目前有一个UIView的子类,其中包含许多subviews。我希望在子视图中添加UISwipeGesture,但遗憾的是无法识别滑动手势。我设置了userInteractionEnabled = true和滑动手势的方向,但没有任何效果。

public class CardStackView: UIView{

  public var dataSource = [UIImage]()
  private var swipeGuesture: UISwipeGestureRecognizer!

  override public func layoutSubviews() {
    for img in dataSource{
      let view = AppView(image: img, frame: self.frame)
      self.addSubview(view)
    }
    animateSubview()
    self.userInteractionEnabled = true
  }

  func animateSubview(){
    for (index, sView) in self.subviews.enumerate() {
     swipeGuesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGuestureDidSwipeRight(_:)))
      swipeGuesture.direction  = .Right
      sView.addGestureRecognizer(swipeGuesture)
      sView.userInteractionEnabled = true
      let move: CGFloat = CGFloat(-20 + index * 20)
      let opacity = Float(1 - 0.2 * CGFloat(index))
      sView.shadowOpacity(opacity).shadowOffset(CGSizeMake(20 - CGFloat(index) * 5, 20 - CGFloat(index) * 5)).shadowRadius(5).moveX(-move).moveY(-move).gravity().shadowColor(UIColor.grayColor()).duration(1)
        .completion({
        }).animate()
    }
  }

  func swipeGuestureDidSwipeRight(gesture: UISwipeGestureRecognizer) {
    print("Swiped right")
    let subview = self.subviews[0]
    subview.moveX(-60).duration(1).animate()
  }


}

示例

class ExampleController: UIViewController {

  var stackView: CardStackView!
  override func viewDidLoad() {
    super.viewDidLoad()
    stackView = CardStackView(frame: CGRect(x: 20, y: 80, width: 200, height: 200))
    stackView.dataSource = [UIImage(named: "2008")!, UIImage(named: "2008")!]
    self.view.addSubview(stackView)
  }

}

2 个答案:

答案 0 :(得分:0)

self.view.bringSubviewToFront(yourSubview)

为您的所有子视图尝试此代码,如果它不起作用,请在您的CardStackView的控制器类中尝试此操作。

答案 1 :(得分:0)

尝试为items致电let unreadCount = items.reduce(0) { $0 + ($1.read ? 0 : 1) }

{{1}}
相关问题