iOS中如何实现循环函数?在Playground重复执行changeButton函数
在iOS Playground中循环执行按钮动画的几种方案
嘿,我来帮你搞定在Playground里重复执行changeButton函数的问题~首先得明确:Playground默认执行完代码就会停止,所以咱们得先设置让它持续运行,然后再选合适的循环方式,下面给你两种最实用的方案:
方案一:递归调用(推荐,动画衔接更流畅)
这种方式会在上一轮所有动画完全结束后,自动启动下一轮,完全不会出现动画重叠的问题,最适合你的场景。只需要在最后一个动画的completion闭包里再次调用changeButton()就行,同时补全你代码里没写完的部分:
import UIKit import PlaygroundSupport // 先创建按钮和承载视图,不然Playground里看不到效果 let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) containerView.backgroundColor = .white let button = UIButton(type: .system) button.setTitle("初始文本", for: .normal) button.frame = CGRect(x: 50, y: 100, width: 200, height: 50) containerView.addSubview(button) // 设置Playground持续运行,不然动画刚启动就停了 PlaygroundPage.current.liveView = containerView PlaygroundPage.current.needsIndefiniteExecution = true func changeButton() { UIView.animate(withDuration: 1.0, delay: 1.0, animations: { button.titleLabel?.alpha = 0.0 }) { _ in button.setTitle("Text", for: .normal) UIView.animate(withDuration: 1.0, delay: 0.0, animations: { button.titleLabel?.alpha = 1.0 }) { _ in UIView.animate(withDuration: 1.0, delay: 1.0, animations: { button.titleLabel?.alpha = 0.0 }) { _ in // 最后一个动画结束后,递归调用自己,实现循环 changeButton() } } } } // 启动第一次动画 changeButton()
方案二:使用Timer(固定间隔循环)
如果你希望不管上一轮动画是否结束,都按固定时间间隔重复执行,可以用Timer。不过要注意:如果你的动画总时长(比如你这里大概是4秒左右)小于Timer的间隔,会有等待;如果大于间隔,会出现动画叠加的情况,所以要根据你的需求调整间隔:
import UIKit import PlaygroundSupport let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) containerView.backgroundColor = .white let button = UIButton(type: .system) button.setTitle("初始文本", for: .normal) button.frame = CGRect(x: 50, y: 100, width: 200, height: 50) containerView.addSubview(button) PlaygroundPage.current.liveView = containerView PlaygroundPage.current.needsIndefiniteExecution = true func changeButton() { UIView.animate(withDuration: 1.0, delay: 1.0, animations: { button.titleLabel?.alpha = 0.0 }) { _ in button.setTitle("Text", for: .normal) UIView.animate(withDuration: 1.0, delay: 0.0, animations: { button.titleLabel?.alpha = 1.0 }) { _ in UIView.animate(withDuration: 1.0, delay: 1.0, animations: { button.titleLabel?.alpha = 0.0 }) } } } // 创建Timer,每隔4秒执行一次changeButton(根据你的动画总时长调整) Timer.scheduledTimer(withTimeInterval: 4.0, repeats: true) { _ in changeButton() }
关键注意点
- 必须设置
PlaygroundPage.current.needsIndefiniteExecution = true,否则Playground执行完初始化代码就会停止,看不到循环动画。 - 要把按钮添加到一个视图里,并设置
PlaygroundPage.current.liveView = 这个视图,不然你看不到按钮和动画效果。
内容的提问来源于stack exchange,提问作者Grazia Bo
相关产品推荐
相关产品推荐

