【问题标题】:UIInterpolatingMotionEffect swift XCodeUIInterpolatingMotionEffect swift XCode
【发布时间】:2014-06-06 07:22:02
【问题描述】:

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

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

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

我也在尝试

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

但是 Xcode 然后返回错误:“Use of unresolved identifier 'TiltAlongHorizo​​ntalAxis'”

【问题讨论】:

    标签: swift


    【解决方案1】:

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

    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 使用了类型推断。编译器可以看到参数的类型应该是UIInterpolatingMotionEffectType,因此我们可以省略它,只指定.TiltAlongHorizontalAxis

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

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

    【讨论】:

    • 谢谢。我的最终代码是 var axis_x_motion: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: UIInterpolatingMotionEffectType.TiltAlongHorizo​​ntalAxis) 和 var axis_x_motion: UIInterpolatingMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type:.TiltAlongHorizo​​ntalAxis) 也在工作跨度>
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 2017-03-22
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多