gpt4 book ai didi

ios - 在 Swift 中创建通用完成处理程序

转载 作者:搜寻专家 更新时间:2023-11-01 06:19:39 25 4
gpt4 key购买 nike

我有一个为新项目创建的通用 NSObject 动画类,我正在尝试使用新类重构一些旧项目。一切都很好,直到我发现一些带有完成 block 的动画,这打乱了我从 View Controller 中删除大量冗余代码的计划。这是我得到的...

Animator.swift

class Animator: NSObject {
var control: UIControl? // Can accept everything that's a subclass of UIControl

override init() {
super.init()
}

// FIXME: figure out how to add a completion block as a parameter on a method call
func animateControl(control: UIControl) {
control.transform = CGAffineTransformMakeScale(0.75, 0.75)
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 5.0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: {
control.transform = CGAffineTransformIdentity
}) { (value: Bool) -> Void in
// completion block
// ** method as a parameter goes here? **
}
}
}

要使用它,而不是输入所有内容来为按钮设置动画,我只需调用 MyViewController.swift

中的类

MyViewController.swift

// Property declaration
let animator = Animator()

// Tie it to an IBAction
@IBAction func myButtonAction(sender: UIButton) {
animator.animateControl(sender, methodIWantToRunAfterAnimateControlFinishes)
}

func methodIWantToRunAfterAnimateControlFinishes() {
// Do Stuff
}

我如何为 animateControl 的初始化程序提供一个方法来作为完成 block 运行?我看了this (不是我的网站,但这是我的感受),但我无法让它工作。

更新

我不得不在语法上费点功夫,但这是让我越过终点线的初始化代码:

func animateControl(control: UIControl, completion: (() -> Void)?) {
control.transform = CGAffineTransformMakeScale(0.75, 0.75)
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 5.0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: {
control.transform = CGAffineTransformIdentity
}) { _ in
// completion block
completion?()
}
}

这处理带有代码的完成 block 和 nil 完成 block 。

最佳答案

当用作参数时,一个非常简单的完成 block 如下所示:

onCompletion: (() -> Void)?

() -> Void 可以为 null ? 的原因是为了在 Objective-C 中可用。如果不需要,则无需将其括在方括号中,也无需将其标记为可为空 ?

这将让您传入一个不需要参数且不返回任何内容的函数。您可以像这样将其添加到您的签名中:

func animateControl(control: UIControl, onCompletion: (() -> Void)?)

如果你想给它添加参数,将它们添加到完成 block 的签名中:

func animateControl(control: UIControl, onCompletion: ((value: AnyObject) -> Void)?)

返回语句也是如此:

func animateControl(control: UIControl, onCompletion: ((value: AnyObject) -> AnyObject)?)

一旦它出现在你的函数签名中,你就可以通过它的名字来调用它了:

func animateControl(control: UIControl, onCompletion: ((value: AnyObject) -> Void)?) {
//do stuff here
onCompletion(obj)
}

关于ios - 在 Swift 中创建通用完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com