ios - 有没有更好的方法在 Swift 中做这个滚动动画?

标签 ios swift animation

我正在尝试向我的应用程序 UI 的一部分添加一个行为,用户可以借此向左滑动,这将导致一组 UILabel 一起同步滚动到屏幕外的左侧,但随后会立即再次滚动回来但从右边开始,但其中包含新信息。

该效果旨在给人一种印象,即您正在从一组信息转移到另一组信息...例如,在开始赛车游戏之前选择一辆汽车...但实际上它是重复使用相同的 View ...滚动到屏幕外以更新其 label.text 信息...然后再次滚动回来。

我已经完成了所有的刷卡操作。我遇到的问题是我的(工作)解决方案:

UIView.animate(withDuration: 0.2, animations: {
        // move label off to the left
        self.titleLabel.center.x -= self.view.bounds.width
    }, completion: {
        $0 ; print("I'm halfway done!")
        // teleport view to a location off to the right
        self.titleLabel.center.x += 2*(self.view.bounds.width)
        // reset label's data
        self.titleLabel.text = NEW_INFO
        // slide label back on screen from the right
        UIView.animate(withDuration: 0.2, animations: {
            self.titleLabel.center.x -= self.view.bounds.width
        }, completion: nil)
    })

感觉很脏,就像穿着别人的内衣。

存在 $0 的唯一原因是让 XCode 停止说:

"Cannot convert value of type '() -> ()' to expected argument type '((Bool) -> Void)?'"

而且我敢肯定,我在完成 block 中制作动画的第二部分这一事实会让我很头疼。

有没有更聪明的方法?

PS - 我宁愿不使用任何预制类,如“ScrollView”或类似的东西......这些 View 都是单独交互的并响应其他回调等。

谢谢!

最佳答案

一个更好的方法是使用 UIPageViewController

这需要一些学习和设置,但比尝试自己滚动要容易得多。

使用 UIPageViewController 的方法是这样的...

创建数据模型...使用您的类比...

struct Car {
    let image: UIImage
    let name: String
}

然后创建一个将显示它的 UIViewController 子类。

class CarViewController: UIViewController {
    var car: Car? {
        didSet {
            displayCar()
        }
    }

    func displayCar() {
        label.text = car?.name
        imageView.image = car?.image
    }
}

然后创建一个 UIPageViewController。在这里面你有一系列的汽车。在函数 func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? 中,你可以创建你的 CarViewController 并传入正确的 Car 来自数组。

这将完成所有的滚动和显示,并且一切仍然是交互式的。

有关其工作原理的更多信息,您可以查看 this one from Ray Wenderlich 等教程.

您还可以使用它来显示页面的一部分(而不是滚动整个屏幕。

关于ios - 有没有更好的方法在 Swift 中做这个滚动动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851075/

相关文章:

ios - 如何将 NSXMLParser 限制为给定元素之后的元素

ios - 将事件门票添加到 Apple 钱包?

Swift 构造函数未出现在方法列表中, "Arguments passed to call that takes no arguments"

Android RecyclerView 将项目移动到 View 的末尾

ios - 在实际旋转之前确定导航栏的新框架 - iOS

iphone - 在 iOS 应用程序中创建另一个具有不同内容的输出设备

ios - 视频并不总是导出到相机胶卷 : NSFileManager's removeItemAtPath non-blocking?

ios - NSManagedObject 在 Swift 中实现协议(protocol)的 EXC_BAD_ACCESS 错误

iphone - iPhone sdk 中最简单的逐帧动画技术是什么?

CSS "fill-mode:forwards"在 Safari 中不工作