首页 > 解决方案 > touchesBegan 语法错误 - 没有成员

问题描述

基本上我要做的是测试用户是点击屏幕的左侧还是右侧。到目前为止,我过去对这段代码没有任何问题。然而,随着 Swift 4 的更新,它给我的语法带来了一些问题。不过,我已经解决了大部分问题。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.anyObject() as UITouch
    let touchLocation = touch.location(in: self) 
    if touchLocation.x < self.frame.size.width / 2 {
        // Left side of the screen
        print("Left")
    } else {
        // Right side of the screen
        print("Right")
    }
}

这一条线我还不能修复。

let touch:UITouch = touches.anyObject() as UITouch 

它给我的错误信息是:

'Set<UITouch>' 类型的值没有成员 'anyObject'

标签: iosswift

解决方案


你需要

guard let touch = touches.first else { return }

推荐阅读