iOS 中的动画文本内容 - 相当于 Android ValueAnimator

2023-11-21

我正在开发一个 iOS 7+ 应用程序,并且想要以动画方式更改 UILabel 的内容。我do not想要做任何图形动画,例如淡出旧内容/淡入新内容。因此,iOS 提供的所有标准动画功能(例如图层动画或动画块)都无法使用(至少我这么认为)。

假设 UILabel 显示一些仪表值,例如“200 V”,并且该文本应更改为“400 V”。文本不应只是从“200 V”跳转到“400 V”,而应使用某种缓动函数进行计数:“200 V”、“220 V”、“240 V”...“390 V”、“395” V”...“400V”

在 Android 中可以使用 ValueAnimator 轻松解决:

ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);
animation.setInterpolation(new EaseOutInterpolator());
animation.setDuration(2500);
animation.setStartDelay(500);

animation.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpate(ValueAnimator animator) {
        float currentValue = animator.getAnimatedValue.floatValue();
        label1.setText(String.format("%.2", fromValue1 + ((toValue1 - fromValue1) * currentValue)));
        label2.setText(String.format("%.2", fromValue2 + ((toValue2 - fromValue2) * currentValue)));
    ...
    }
});
animation.start();

iOS 里也有这样的东西吗?我为此找到了不同的解决方案,但它们都相当旧(2010/11),并且最终都使用 NSTimer 和自己的缓动函数手动实现此行为。

毫无疑问,一个人可以自己实现这一点,但这会相当麻烦,而且不太优雅。那么:iOS 中是否有内置的东西可以解决这个问题,或者至少有方便的第三方实现可用?

非常感谢!


由于我没有找到为此量身定制的解决方案,因此我创建了自己的解决方案:一个处理缓动的简单动画器类:

// MyValueAnimation.h
typedef void (^MyAnimationBlock)(double animationValue);

@interface MyValueAnimation : NSObject

- (void)startAnimation:(MyAnimationBlock)animationBlock runtime:(NSUInteger)runtime delay:(NSUInteger)delay;

@end


// MyValueAnimation.m
#import "MyValueAnimation.h"

// Number of seconds between each animation step
#define kStepSize 0.05

@interface MyValueAnimation () {
    NSTimer *timer;            
    NSUInteger totalRunTime;    // Total duration of the animation (delay not included)
    NSUInteger currentRuntime;  // Time the animation is already running
    MyAnimationBlock animationBlock;
}
@end

@implementation MyValueAnimation

- (void)startAnimation:(MyAnimationBlock)block runtime:(NSUInteger)runtime delay:(NSUInteger)delay {
    if (timer != nil)
        [timer invalidate];

    timer = nil;
    totalRunTime = runtime;
    animationBlock = block;
    currentRuntime = 0;

    if (block != nil) {
        if (delay > 0) {
            // Wait to delay the start. Convert delay from millis to seconds
            double delaySeconds = (double)delay / 1000.0;
            timer = [NSTimer scheduledTimerWithTimeInterval:delaySeconds target:self selector:@selector(delayTick:) userInfo:nil repeats:false];
        } else {
            // Run the animation
            timer = [NSTimer scheduledTimerWithTimeInterval:kStepSize target:self selector:@selector(animationTick:) userInfo:nil repeats:true];
        }
    }
}

- (void)delayTick:(NSTimer *)delayTimer {
    // End of delay -> run animation
    [delayTimer invalidate];
    timer = [NSTimer scheduledTimerWithTimeInterval:kStepSize target:self selector:@selector(animationTick:) userInfo:nil repeats:true];
}

- (void)animationTick:(NSTimer *)animationTimer {
    NSUInteger step = 1000 * kStepSize;  // step size/length in milli seconds
    currentRuntime += step;
    double progress = MIN((double)currentRuntime / (double)totalRunTime, 1.0);

    // Progress is a value between 0 and 1. The easing function maps this
    // to the animationValue which is than used inside the animationBlock
    // to calculate the current value of the animiation
    double animationValue = [self customEaseOut:progress];

    if (animationBlock != nil)
        animationBlock(animationValue);

    if (progress >= 1.0) {
        // Animation complete
        [timer invalidate];
        timer = nil;
    }        
}

- (double)customEaseOut:(double)t {
    // Use any easing function you like to animate your values...
    // http://rechneronline.de/function-graphs/
    // http://sol.gfxile.net/interpolation/
    return (1 - pow(1-t, 2));
}

@end 


// =============================================================

// Some code using the animation
- (void)animateValueFrom:(double)fromValue to:(double)toValue {
    if (valueAnimation == nil)
        valueAnimation = [[MyValueAnimation alloc] init];

    MyAnimationBlock animationBlock = ^(double animationValue) {
        double currentValue = fromValue + ((toValue - fromValue) * animationValue);

        someLabel.text = [NSString stringWithFormat:"%dV", currentValue];        
    };

    [valueAnimation startAnimation:animationBlock runtime:1500 delay:500];
}

也许不是最漂亮的解决方案,但它有效:-)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS 中的动画文本内容 - 相当于 Android ValueAnimator 的相关文章

  • TestFlight 提供反馈按钮

    我正在使用 iOS 8 的最新 testflight 版本 我将自己添加为内部测试人员 现在当我使用 testflight 打开应用程序时 我找不到反馈按钮 如果有人有任何线索 请告诉我 您在 Testflight 应用程序中提供反馈 打开
  • NSCalendar 返回明年第一周上周一的错误日期

    我使用下面的代码使用随机日期来计算上周一 哪个工作文件但我的代码在明年日期中断 下面是相同的代码 NSDate date NSDate dateWithTimeIntervalSince1970 1483620311 228 NSLog c
  • Swift 3:如何访问48字节CFData中matrix_float3x3的值?

    我正在尝试访问内在矩阵answer https stackoverflow com a 48159895 9296667 通过运行下面的命令 我能够得到一个 48 字节的任意对象 https developer apple com docu
  • 如何在 Swift 中将文件名与文件扩展名分开?

    给定包中文件的名称 我想将该文件加载到我的 Swift 应用程序中 所以我需要使用这个方法 let soundURL NSBundle mainBundle URLForResource fname withExtension ext 无论
  • NSString stringWithContentsOfFile 失败,错误代码似乎错误

    我正在尝试将文件加载到字符串中 这是我正在使用的代码 NSError error nil NSString fullPath NSBundle mainBundle pathForResource filename ofType html
  • 无法连接到 iTunes Store(获取应用内购买列表)

    我正在尝试从我的应用程序的应用程序内购买项目商店中获取列表 这是我所做的 安装了新的配置文件并启用了应用内购买 替换配置文件很棘手 但我认为我的设置是正确的 验证税务和银行信息是否正常 该应用程序已在商店出售 创建测试用户 在测试设备上以测
  • 如何找到键盘未覆盖的视图部分(UIModalPresenationStyleFormSheet)?

    我有一个视图控制器 显示带有 UITextView 的视图 并且我想在键盘出现时调整视图的大小 以便 UITextView 不会被键盘覆盖 我几乎在所有情况下都可以正常工作 据我所知 仅当视图控制器以 ModalPresentationSt
  • 如何开始复杂级别的跨平台移动应用开发? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • `navigator.geolocation.getCurrentPosition()` 在 iOS PWA 上挂起

    我有这个片段 const getCurrentPosition gt new Promise
  • 从 UIPickerView 的选定行设置 UIButton 的标题

    详细场景是这样的 我使用循环创建 10 个按钮并设置 0 9 的标签 点击每个按钮时 我将调用 UIPickerView 在其中加载来自不同数组的数据 到这里我就得到了预期的结果 但我希望 pickerView 中选定的行应设置为相应按钮的
  • iOS 中 NSDecimalNumber 的小数分隔符错误

    我尝试通过以下方式输出具有正确的小数分隔符的十进制数的描述 NSString strValue 9 94300 NSDecimalNumber decimalNumber NSDecimalNumber decimalNumberWithS
  • (Kiss)XML xpath 和默认命名空间

    我正在开发一个 iPhone 项目 需要解析一些 xml xml 可能包含也可能不包含默认名称空间 我需要知道如何解析 xml 以防它使用默认命名空间 由于我需要读取和写入 xml 因此我倾向于使用 KissXML 但我愿意接受建议 这是我
  • 如何让UITextView背景线与文字对齐?

    我正在尝试绘制 UITextView 的背景线 这是我用来画这些线的代码 CGContextBeginPath context CGContextSetStrokeColorWithColor context self horizontal
  • AVAssetExportSession 无法导出从 iCloud 下载的视频

    我正在尝试创建从用户相册中选择的视频的缩小版本 输出的最大尺寸为 720p 因此 在检索视频时 我使用 mediumQualityFormat as the deliveryMode 如果用户设备中不存在原始视频或其中等质量版本 这会导致
  • 调整 UIImage 的大小而不将其完全加载到内存中?

    我正在开发一个应用程序 用户可以在其中尝试加载非常非常大的图像 这些图像首先在表格视图中显示为缩略图 我的原始代码会在大图像上崩溃 因此我重写它以首先将图像直接下载到磁盘 是否有一种已知的方法可以调整磁盘上图像的大小 而无需通过以下方式将其
  • watchOS 错误:控制器接口描述中的未知属性

    我将 WKInterfacePicker 添加到情节提要中 并将其连接到界面控制器中的 IBOutlet 运行应用程序时 它在控制台中显示一条错误消息 控制器的接口描述 watchPicker 中的未知属性 Code interface I
  • 在requestAnimationFrame中使用clearRect不显示动画

    我正在尝试在 HTML5 画布上做一个简单的 javascript 动画 现在我的画布是分层的 这样当我收到鼠标事件时 背景层不会改变 但带有头像的顶层会移动 如果我使用 requestAnimationFrame 并且不清除屏幕 我会看到
  • 如何在 UICollectionView 中将行居中?

    我有一个UICollectionView与随机细胞 有什么方法可以让我将行居中吗 默认情况下它是这样的 x x x x x x x x x x x x x x 这是所需的布局 x x x x x x x x x x x x 我必须做这样的事
  • 像 TraceGL 一样分析 Objective C 中的代码路径?

    TraceGL 是一个非常简洁的项目 它允许 JS 程序员跟踪 Javascript 中的代码路径 它看起来像这样 我想为 Objective C 构建类似的东西 我知道运行时使跟踪方法调用变得相当容易 但是我如何跟踪控制流 例如 在上面的
  • ios - 如何声明静态变量? [复制]

    这个问题在这里已经有答案了 C 中声明的静态变量如下 private const string Host http 80dfgf7c22634nbbfb82339d46 cloudapp net private const string S

随机推荐

  • SQL标签列表和标签过滤

    我有一个 SQL 数据库 其中存储用户和与用户关联的标签 多对多关系 我有经典的模式users table tags表和 桥 表usertag它将用户与标签链接起来 users table Id Name 1 Alice 2 Bob 3 C
  • 从任务<>获取对象

    我有以下方法 private async Task
  • Android 重定向不起作用

    我需要在 javascript 文件中重定向到用户指定的给定 URI 一个简单的例子 我是如何做到这一点的 function redirect uri if navigator userAgent match Android i docum
  • Excel 用户窗体显示的大小错误

    我在使用 Excel UserForms 时遇到一个非常奇怪的问题 当我通过单击工作表中的命令按钮来显示表单时 表单的大小会显着变形 使其基本上无法使用 下图说明了这一点 Form before size warping intended
  • Python 中的不可排序类型错误是什么意思?

    from urllib request import urlopen page1 urlopen http www beans r us biz prices html page2 urlopen http www beans r us b
  • Django CSRF 验证失败。请求中止。- CSRF cookie 未设置

    我知道这个问题以前已经被问过 我几乎尝试了人们给出的所有选项 但我似乎无法解决它 我是一个完全的新手 所以请让我知道我哪里出错了 我正在尝试编写一个简单的原始表单 到目前为止 我还没有实现任何身份验证或会话机制 但从我所读到的内容来看 这与
  • 在 64 位 Windows 上运行 cURL

    我是 cURL 的新手 刚刚安装它 但它似乎只做它感觉像的事情 我使用的是从这里获得的 64 位版本 http curl haxx se latest cgi curl win64 ssl sspi我在这里找到了安装说明 http guid
  • 如何使用Fiddler监听asp.net开发服务器(即cassini)?

    我正在尝试使用 Fiddler 调试 RESTful WCF 应用程序 我通过 VS IDE 运行我的项目 它在 ASP NET 开发服务器 又名 Cassini 中启动我的应用程序 然后 我启动 Fiddler 并在 请求生成器 选项卡中
  • C 语言最佳实践中的项目组织

    我想知道组织大型 C 项目的最佳实践是什么 它是一个专业项目 而不是开源项目 可能存储在 Git 存储库中 事情应该如何排序 结构应该去哪里 什么时候应该使用附加到结构的函数而不是使用结构作为参数的函数 就在项目中布置文件而言 应该如何组合
  • .Net Core 依赖注入从构造函数中注入

    我需要从构造函数中注入我在安装程序中声明的所有内容 我可以做吗 如何从构造函数中注入服务 类似于 Angular 2 中的 Injector 服务 在控制器中无需构造函数即可注入服务 像这样的东西 public class Controll
  • Android 中的人脸检测?

    我目前正在开发一个实验性相机应用程序 我目前正在考虑实施人脸检测 并正在权衡我的选择 我已经考虑过可用于 Android 的 OpenCV 端口并使用其人脸检测功能 但从我之前看到的实现的演示来看 相机似乎滞后很多 考虑到 HTC Desi
  • 如何计算R中每一行字符串的频率

    我有一个看起来像这样的 txt 文件 rs1 NC AB NC rs2 AB NC AA rs3 NC NC NC 对于每一行 我想计算 NC 的频率 这样我的输出将如下所示 rs1 2 rs2 1 rs3 3 有人可以告诉我如何在 R 或
  • 有没有办法在 PHP 中将 json 转换为 xml?

    有什么办法可以转换吗json to xml in PHP 我知道xml到json是很有可能的 如果您愿意使用XML序列化器从 PEAR 中 您可以通过两个简单的步骤将 JSON 转换为 PHP 对象 然后将 PHP 对象转换为 XML in
  • Visual Studio 中的 C++20 支持

    我想用std format但 Visual Studio 说std命名空间没有成员format 这对于 C 20 来说似乎是新的 有办法让它可用吗 截至撰写本文时 还没有 C 标准库实现std format 网络上有各种可用的实现 例如ht
  • 无法使用 make-symbol 生成的名称调用宏中定义的函数

    我正在尝试写一个ELisp宏根据一些通用数据生成多个函数 例如 当我想计算 fn 名称时 我会写类似的内容 我暂时忽略了卫生 我将符号文字传递到宏中 因此评估不重要 cl defmacro def fns sym SYM let s1 ma
  • 错误 azure-pipelines.yml 中出现意外值“步骤”

    我试图在构建和部署 docker image 之前将视频文件从 GPM 复制到 app dist asset images 文件夹 在第 27 行获取意外值 Steps 如果我删除复制视频文件的步骤 YML 文件可以正常工作 azure p
  • 如何在 asp.net 页面上的 <% ... %> 标记内使用 C# 代码?

    我正在编写一个 asp net 用户控件 它有一个属性FurtherReadingPage 和两个与其绑定的控件 ObjectDataSource 和Repeater 在中继器内 我想显示一个超链接 其 href 属性设置为类似Furthe
  • Access-Control-Allow-Headers 不允许使用 $http 请求标头字段

    我正在做一个POST到使用的服务邮递员 Chrome 扩展 我得到了预期的响应 但是 当我做同样的事情时POST请求使用 http 一切都见鬼去吧 我得到一个 Request header field Engaged Auth Token
  • dplyr 过滤器函数:如何返回每个值(或“取消”过滤器的效果)?

    这似乎是一个奇怪的问题 但是有没有一种方法可以将值传递给基本上不执行任何操作的 filter data cars library dplyr cars gt filter speed magic value that returns car
  • iOS 中的动画文本内容 - 相当于 Android ValueAnimator

    我正在开发一个 iOS 7 应用程序 并且想要以动画方式更改 UILabel 的内容 我do not想要做任何图形动画 例如淡出旧内容 淡入新内容 因此 iOS 提供的所有标准动画功能 例如图层动画或动画块 都无法使用 至少我这么认为 假设