首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Swift同时检测屏幕左右两侧的触摸

Swift同时检测屏幕左右两侧的触摸
EN

Stack Overflow用户
提问于 2017-03-01 06:07:45
回答 3查看 1.4K关注 0票数 3

我已经能够检测到用户是在触摸屏幕的左侧还是右侧,然后执行某个功能。我正在尝试检测屏幕的两侧是否同时被触摸,如果是,则执行另一个功能。

这就是我所拥有的,当屏幕的两侧同时被触摸时,它就不起作用了。

这在update函数中。

代码语言:javascript
运行
复制
if (touched) {
        var isRight : Bool = false
        var isLeft : Bool = false

        if(location.x < 0){
        isLeft = true
        moveLeft()
        }
        else if(location.x > 0){
        isRight = true
        moveRight()


            }
        else if (isRight && isLeft){
            moveUp()


        }

    }
EN

回答 3

Stack Overflow用户

发布于 2017-03-01 06:57:02

下面检查触摸端的所有接触,并将联合值构建为整数值,然后可以使用switch语句进行检查:

代码语言:javascript
运行
复制
struct Sides : OptionSet {
    let rawValue: Int

    static let left = Sides(rawValue:1)
    static let right = Sides(rawValue:2)

    static let both : Sides = [.left, .right]
    static let none : Sides = []
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // Get sides touched
    let touched = touches.map { return $0.location(in: view) }.reduce(Sides.none) {
        if $1.x < 0 {
            return [ $0, Sides.left ]
        }
        else if $1.x > 0 {
            return [ $0, Sides.right ]
        }
        else {
            return $0
        }
    }

    switch(touched) {
    case Sides.left:
        // handle left
        break

    case Sides.right:
        // handle right
        break

    case Sides.both:
        // handle both
        break

    case Sides.none:
        fallthrough

    default:
        // none
        break

    }
}
票数 1
EN

Stack Overflow用户

发布于 2017-03-01 06:56:43

使用此函数获取触摸位置的数组,以测试它们的位置是否为(左和右)

代码语言:javascript
运行
复制
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.count == 2 {
        // 2 touches so we got 2 positions
        let tch_1 = touches[touches.startIndex].location(in: self.view)
        let tch_2 = touches[touches.endIndex].location(in: self.view)
        if (tch_1.x < self.view.frame.size.width / 2 && tch_2.x >= self.view.frame.size.width / 2) || (tch_2.x < self.view.frame.size.width / 2 && tch_1.x >= self.view.frame.size.width / 2) {
            //touch detected in both left and right side of screen simultaneously

        }
    }
}
票数 0
EN

Stack Overflow用户

发布于 2017-03-01 06:24:02

我没有时间写代码(我现在正在打电话--如果你发布所有的函数会有帮助的)。基本上,你应该得到一个触摸数组作为参数。然后迭代它们并打开标志:右/左触摸。然后根据标志调用您的函数

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42519639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档