【问题标题】:Touch Location and touchesBegan in Xcode 6 [Obj-C --> Swift]Xcode 6 中的 Touch Location 和 touchesBegan [Obj-C --> Swift]
【发布时间】:2014-08-24 17:41:26
【问题描述】:

我在创建函数“touchesBegan”然后创建一个 UIPoint 和 UITouch 常量或变量来保存 x 和 y 坐标时遇到问题。我在 Objective-C 中有我想要的确切代码,但我不知道它在 Swift 中的等价物是什么。这是我想基本上翻译成 Swift 代码的 Objective-C 代码... 注意:这是一个单视图应用程序,而不是游戏...提前致谢。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];

    if (point.x < 160) {
        var = 10;
    }
    else{
        var = 20;
    }

}

【问题讨论】:

    标签: ios objective-c xcode swift touchesbegan


    【解决方案1】:

    从 Swift 1.2 开始,使用这个

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
    {
    
        var touch = touches.first as! UITouch
        var point = touch.locationInView(self)
    
        if point.x < 160 {
            var = 10;
        }
        else{
        var = 20;
        }
    }
    

    【讨论】:

      【解决方案2】:

      问题出在哪里?

      var touch = touches.anyObject() as! UITouch
      var point = touch.locationInView(self.view)
      
      if point.x < 160 {
          var variableName = 10;
      }
      else{
          var variableName = 20;
      }
      

      【讨论】:

        【解决方案3】:

        Swift 1.2 更改了 touchesBegan 的语法。请参阅UIResponder Reference

        func touchesBegan(_ touches: Set<NSObject>, withEvent event: UIEvent)
        

        别忘了引用 super。

        super.touchesBegan(touches, withEvent: event)
        

        这是一个从techotopia.com 实现此代码的经过编辑的示例,它可能会为您提供有关其他三个触摸功能的更多信息。

        override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
           var touch = touches.anyObject() as! UITouch
           var point = touch.locationInView(self.view)
           // Insert if statements
           super.touchesBegan(touches, withEvent: event)
        }
        

        【讨论】:

        • 这在 swift 1.2 中不起作用,MendyK 的答案是正确的
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-24
        • 1970-01-01
        • 1970-01-01
        • 2014-07-26
        • 1970-01-01
        相关资源
        最近更新 更多