UIInterpolatingMotionEffect swift XCode

时间:2014-06-06 07:22:03

标签: swift

我正在尝试用新语言Swift中的代码定义动作效果

var axis_x_motion: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect( "center.x", UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis)

但Xcode会返回错误:"使用未解析的标识符' UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis'"

我也在尝试

var axis_x_motion: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect( "center.x", TiltAlongHorizontalAxis)

但Xcode会返回错误:"使用未解析的标识符' TiltAlongHorizo​​ntalAxis'"

2 个答案:

答案 0 :(得分:2)

在我进行解释之前,让我们看一下纠正后的代码

var axisXMotion = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)

作为一个简单的信息,Swift语言的惯例是使用CamelCase而不是snake_case。

对,这些变化意味着什么。 Swift使用命名参数的概念,并要求您在大多数情况下使用这些参数名称。例如,如果我们查看UIInterpolatingMotionEffect的初始化器,我们可以看到它需要两个参数,

init(keyPath: String!, type: UIInterpolatingMotionEffectType)

这些参数的名称为keyPathtype,因此我们需要在调用中指定它们。

对于无法识别的标识符,这归结为Swift如何识别枚举值。在C中,我们能够以UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis的方式提供标识符的名称。但是在Swift中我们需要提供枚举的名称和大小写,如下所示:

UIInterpolatingMotionEffectType.TiltAlongHorizontalAxis

但是你可以看到我没有指定之前的UIInterpolatingMotionEffectType部分。这是因为Swift使用 Type Inference 。编译器可以看到参数应该是UIInterpolatingMotionEffectType类型,因此允许我们省略它并只指定.TiltAlongHorizontalAxis

您还可以在创建变量时使用此类型推断。编译器知道UIInterpolatingMotionEffect的初始化器将返回类型为UIInterpolatingMotionEffect的对象,因此可以推断出所需的类型,从而允许您省略它。

我希望这有助于解释其中的一些问题,如果您需要更多帮助或解释,请问!

答案 1 :(得分:0)

Swift使用新的点语法来访问枚举值。您必须将枚举名称(UIInterpolatingMotionEffectType)和您要访问的特定成员值(TiltAlongVerticalAxis)组合在一起,如下所示:

var axis_x_motion: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect("center.x", UIInterpolatingMotionEffectType.TiltAlongVerticalAxis)