在Xcode 6中触摸位置和触摸开始[Obj-C - >迅速]

时间:2014-08-24 17:41:27

标签: ios objective-c xcode swift touchesbegan

我无法创建函数“touchesBegan”,然后创建一个包含x和y坐标的UIPoint和UITouch常量或变量。我在Objective-C中有我想要的确切代码,但我不知道它在Swift中的含义是什么。这是Objective-C代码,我想基本上转换成Swift代码...... 注意:这是单视图应用程序,而不是游戏......提前致谢。

-(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;
    }

}

3 个答案:

答案 0 :(得分:13)

从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;
    }
}

答案 1 :(得分:5)

问题出在哪里?

var touch = touches.anyObject() as! UITouch
var point = touch.locationInView(self.view)

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

答案 2 :(得分:-1)

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

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

不要忘记引用超级。

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)
}