以编程方式将UIView添加到UIScrollView不会捕获UITapGestureRecognizer

时间:2018-04-17 22:23:22

标签: ios swift uiscrollview uitapgesturerecognizer

我正在使用Swift 4开发应用,并针对iOS 9及更高版本。对于视图,我已经建立了一个UIScrollView,如下面的帖子所示:

https://medium.com/@pradeep_chauhan/how-to-configure-a-uiscrollview-with-auto-layout-in-interface-builder-218dcb4022d7

所以我的测试应用程序看起来像这样:

Storyboard status corresponds to the final step of the link above

我的项目是基于cocoapods的,所以我添加了FlexLayout和PinLayout库,用于自定义布局我的UIView。我以编程方式在scrollview的视图容器中添加了自定义UIViews(如卡片),并且在实例化时为每个UIView添加了一个UITapGestureRecognizer到这样的实例。

的ViewController:

func drawRows() {
    flexContainer.flex.direction(.column).define {
        (mainFlex) in
        for i in 0..<15 {
            let newCard = EmptyCard(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
            newCard.backgroundColor = .lightGray
            let label = UILabel(frame: CGRect(x: 10, y: 10, width: 100, height: 50))
            label.text = "Card: \(i)"
            newCard.addSubview(label)
            mainFlex.addItem(newCard).marginLeft(10).marginBottom(5).width(200).height(100)
        }
    }
    contentView.addSubview(flexContainer)
    flexContainer.pin.all()
    flexContainer.flex.layout(mode: .adjustHeight)
    scrollView.contentSize = flexContainer.frame.size
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    drawRows()
}

每张卡都有下一个类定义:

import UIKit

class EmptyCard: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        addGestureToCard()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addGestureToCard()
    }

    func addGestureToCard() {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(handleOnTap))
        gesture.cancelsTouchesInView = false
        self.addGestureRecognizer(gesture)
        self.isUserInteractionEnabled = true
    }

    @objc func handleOnTap(sender : UITapGestureRecognizer) {
        print("Hola Mundo")
    }
}

结果如下:

resulting UI

当我点击一开始未显示的UIView时会出现问题,因为它是在UIScrollView的坐标中添加的,该坐标远离设备尺寸,例如卡片6及其上方的水龙头手势识别器没有&# 39;工作

cards that don't have the gesture recognizer active

对于其余的UIViews(最初适合设备尺寸的那些,即Card 0,Card 1,Card 2,Card 3,Card 4和Card 5的顶部),手势识别器工作正常,即,&#34; Hola Mundo&#34;字符串消息显示在调试控制台中。我试图修复问题,给视图容器(滚动视图内部的那个)提供固定尺寸,但这确实不起作用。我希望有人对这种情况有所了解,谢谢你提前。

0 个答案:

没有答案