You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发:如何用Objective-C在LaunchScreen.xib动态添加当前年份至Label

当然可以实现!

虽然LaunchScreen默认是静态展示的,但我们可以通过简单的技巧在App启动后立刻动态替换Label内容,实现显示当前年份的需求。下面是具体的操作步骤:

步骤1:配置LaunchScreen.xib中的Label

  • 打开你的LaunchScreen.xib,添加一个UILabel到合适位置,设置好字体、颜色、对齐方式等样式
  • 设置Label的默认文本为类似Copyright © [Year]的占位内容(方便你确认位置是否正确)
  • 选中这个Label,在右侧Identity Inspector(第三个标签)的Accessibility区域,设置Accessibility Identifier为copyrightLabel(这个标识用来后续定位该控件)

步骤2:编写Objective-C代码动态替换年份

根据你的iOS版本,选择对应的位置添加代码:

情况1:iOS 12及以下(使用AppDelegate)

打开AppDelegate.m,在application:didFinishLaunchingWithOptions:方法中添加以下代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 获取当前年份
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy"];
    NSString *currentYear = [dateFormatter stringFromDate:[NSDate date]];
    
    // 获取LaunchScreen所在窗口并找到目标Label
    UIWindow *launchWindow = [[UIApplication sharedApplication] windows].firstObject;
    UILabel *copyrightLabel = [launchWindow viewWithAccessibilityIdentifier:@"copyrightLabel"];
    
    // 替换文本
    if (copyrightLabel) {
        copyrightLabel.text = [NSString stringWithFormat:@"Copyright © %@", currentYear];
    }
    
    return YES;
}

情况2:iOS 13及以上(使用SceneDelegate)

打开SceneDelegate.m,在scene:willConnectToSession:options:方法中添加以下代码:

- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
    // 获取当前年份
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy"];
    NSString *currentYear = [dateFormatter stringFromDate:[NSDate date]];
    
    // 获取LaunchScreen所在窗口并找到目标Label
    UIWindow *window = ((UIWindowScene *)scene).windows.firstObject;
    UILabel *copyrightLabel = [window viewWithAccessibilityIdentifier:@"copyrightLabel"];
    
    // 替换文本
    if (copyrightLabel) {
        copyrightLabel.text = [NSString stringWithFormat:@"Copyright © %@", currentYear];
    }
}

注意事项

  • 这个操作是在App启动后立刻执行的,用户几乎不会察觉到静态占位文本和动态年份的切换
  • 不要在LaunchScreen中做复杂的逻辑操作,避免拖慢App启动速度
  • 确保Accessibility Identifier设置正确,否则会找不到目标Label
  • 测试时记得用冷启动(完全关闭App后重新打开)验证效果,热启动可能不会重新加载LaunchScreen

内容的提问来源于stack exchange,提问作者Simant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:32:10