我正在用Objective-C为iOS7开发一个应用程序.我的应用程序里有一个屏幕,上面有几个按钮和漂亮的背景图片.(这是一个简单的XIB,在UIImageView的基础上再加上UIButtons.)

我在想,如果这些按钮具有iOS 7主屏幕所具有的视差效果,那就太酷了,所以如果你倾斜手机,你可以看到背景.

我怎样才能在我自己的应用程序中实现这种效果呢?

推荐答案

在iOS7中,苹果引入了UIMotionEffect来添加与用户设备方向相关的运动效果.例如,要在主屏幕上模拟视差效果,您可以使用子类UIInterpolatingMotionEffect,如所解释的here,只需几行代码.

Objective-C:

// Set vertical effect
UIInterpolatingMotionEffect *verticalMotionEffect = 
  [[UIInterpolatingMotionEffect alloc] 
  initWithKeyPath:@"center.y"
             type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
verticalMotionEffect.minimumRelativeValue = @(-10);
verticalMotionEffect.maximumRelativeValue = @(10);

// Set horizontal effect 
UIInterpolatingMotionEffect *horizontalMotionEffect = 
  [[UIInterpolatingMotionEffect alloc] 
  initWithKeyPath:@"center.x"     
             type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
horizontalMotionEffect.minimumRelativeValue = @(-10);
horizontalMotionEffect.maximumRelativeValue = @(10);
  
// Create group to combine both
UIMotionEffectGroup *group = [UIMotionEffectGroup new];
group.motionEffects = @[horizontalMotionEffect, verticalMotionEffect];

// Add both effects to your view
[myBackgroundView addMotionEffect:group];

Swift(感谢@Lucas):

// Set vertical effect
let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y",
type: .TiltAlongVerticalAxis)
verticalMotionEffect.minimumRelativeValue = -10
verticalMotionEffect.maximumRelativeValue = 10

// Set horizontal effect
let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x",
    type: .TiltAlongHorizontalAxis)
horizontalMotionEffect.minimumRelativeValue = -10
horizontalMotionEffect.maximumRelativeValue = 10

// Create group to combine both
let group = UIMotionEffectGroup()
group.motionEffects = [horizontalMotionEffect, verticalMotionEffect]

// Add both effects to your view
myBackgroundView.addMotionEffect(group)

此外,您还可以找到一系列库来简化此操作,或将此功能添加到较旧的iOS版本:

Ios相关问答推荐

连接一些字符串,每个字符串都应该可以在swiftUI中单独点击

Swift:从字符串目录获取带有参数的本地化字符串

Xcode15.3上的生成错误:调用的对象类型';facebook::flipper::SocketCertificateProvider';不是函数或函数指针

SWIFT用户界面检测手势的开始和结束

在TVOS中访问SWIFT中的objc++函数时发送给类的无法识别的 Select 符

在 Android 和 iOS 应用程序上下文中阻止后台线程有哪些缺点?

_SKStoreProductParameterAdNetworkSourceIdentifier未定义符号

工具栏底部 iOS 16 - SwiftUI

SwiftUI 解除 .alert 弹出 NavigationView

react 在 android 上运行的本机应用程序,但在 iOS 上出现问题,详细信息在描述中共享

AVPlayer 退出全屏

SwiftUI:添加核心数据项时更新选项卡栏徽章

UICollectionView - 动态单元格高度?

Got Unrecognized selector -replacementObjectForKeyedArchiver: 在 Swift 中实现 NSCoding 时崩溃

导航控制器自定义过渡动画

在原生和 phonegap 之间挣扎,简单的应用需求

水平滚动 UICollectionView 时对齐单元格的中心

NSURLSession:如何增加 URL 请求的超时时间?

测试目标 X 遇到错误(提前意外退出,操作从未完成 bootstrap - 不会try 重新启动

具有两种不同字体大小的 NSAttributedString 示例?