Array.contains(where :)返回返回true的Array项

时间:2017-10-26 20:41:40

标签: ios arrays swift contains

在Swift中,我们说有一个可拖动的UIButton可以放在很多视图上。参考View的最快捷方式是什么?

let Array: [UIViews] = [View1, View2, View3, View4, View5, View6]

func oneFingerSwipe(_ gesture:UIPanGestureRecognizer){
    let pointInView = gesture.location(in: gesture.view)

    switch(gesture.state){
            case .changed:
                Button.center = CGPoint(x: pointInView.x, y: pointInView.y)
            case .ended:
                if Array.contains(where: { $0.frame.contains(pointInView)}) {
                    // do something to said View($0) through either Array[index] or reference to the View($0)
                }

// INWEAD of long winded

                if View1.frame.contains(pointInView) {
                    //do work to View1
                } else if View2.frame.contains(pointInView) {
                    //do work to View2
                } else if View3.frame.contains(pointInView) {
                    //do work to View3
                } else if View4.frame.contains(pointInView) {
                    //do work to View4
                } else if View5.frame.contains(pointInView) {
                    //do work to View5
                } else if View6.frame.contains(pointInView) {
                    //do work to View6
                }
            default: break
    }
}

1 个答案:

答案 0 :(得分:3)

您应该能够过滤视图数组并使用first(where:)函数获取第一个匹配的视图:

if let targetView = Array.first(where: {$0.frame.contains(pointInView)} ) {
    ...
}