Views Visible部分上的触摸事件iOS Swift 4

时间:2018-08-09 10:35:22

标签: ios swift events touch

我正在/Modules/MarkLogic/data-hub-framework/中的 Photo Collage 上工作,我已经使用Swift4如下创建了拼贴画

enter image description here

我在UIBezierPath中有5个滚动视图,下面是Storyboard的顺序

enter image description here

使用以下代码创建形状

Scrollviews

现在的问题是, var path1 = UIBezierPath() path1.move(to: CGPoint(x: 0, y: 0)) path1.addLine(to: CGPoint(x: superView.frame.width / 2, y: 0)) path1.addLine(to: CGPoint(x: 0, y: superView.frame.width / 2)) path1.addLine(to: CGPoint(x: 0, y: 0)) var borderPathRef1 = path1.cgPath var borderShapeLayer1 = CAShapeLayer() borderShapeLayer1.path = borderPathRef1 scroll1.layer.mask = borderShapeLayer1 scroll1.layer.masksToBounds = true var path2 = UIBezierPath() path2.move(to: CGPoint(x: 0, y: 0)) path2.addLine(to: CGPoint(x: superView.frame.width / 2, y: 0)) path2.addLine(to: CGPoint(x: superView.frame.width / 2, y: superView.frame.width / 2)) path2.addLine(to: CGPoint(x: 0, y: 0)) var borderPathRef2 = path2.cgPath var borderShapeLayer2 = CAShapeLayer() borderShapeLayer2.path = borderPathRef2 scroll2.layer.mask = borderShapeLayer2 scroll2.layer.masksToBounds = true 位于顶部,因此我无法获得Scrollviews的触摸事件。我想触摸Scroll5Scroll1等重叠视图。简而言之,我需要触摸事件以显示可见区域的特定视图。

在需要触摸视图的位置查看下面的图像。

enter image description here

如何联系Scroll2

请帮助!

1 个答案:

答案 0 :(得分:1)

必须确保首先将滚动视图的超级视图设置为 isUserInterfaceEnabled = true

要获取重叠的视图触摸事件:

这是我的代码:

class CustomView: UIView {
let view1: UIView
let view2: UIView
let view3: UIView
let view4: UIView
let view5: UIView

override init(frame: CGRect) {
    view1 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    view1.backgroundColor = UIColor.black
    view1.isUserInteractionEnabled = true
    view2 = UIView(frame: CGRect(x: 100, y: 0, width: 100, height: 100))
    view2.backgroundColor = UIColor.orange
    view2.isUserInteractionEnabled = true
    view3 = UIView(frame: CGRect(x: 0, y: 100, width: 100, height: 100))
    view3.backgroundColor = UIColor.blue
    view3.isUserInteractionEnabled = true
    view4 = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
    view4.backgroundColor = UIColor.brown
    view4.isUserInteractionEnabled = true
    view5 = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    view5.tag = 121
    view5.backgroundColor = UIColor.red
    super.init(frame: frame)
    self.addSubview(view1)
    self.addSubview(view2)
    self.addSubview(view3)
    self.addSubview(view4)
    self.addSubview(view5)
    view1.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(touchAction)))
}

@objc func touchAction () {
    print("----------- touch view 1")
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    if (view1.point(inside: self.convert(point, to: view1), with: event)) {
        return view1
    }
    return self
}

}

函数 hitTest 决定要触摸的是哪个视图,因此只需要返回重叠的视图即可。