关于NSTimeInterval的使用

本文解释了如何使用NSDate和NSTimeInterval进行时间转换,并展示了如何轻松计算两个时间点之间的秒差。
NSTimeInterval time = [[NSDate date] timeIntervalSince1970]; 可以这样定义
NSLog(@"当前时间为%f", time); 打印出从1970年开始到现在的秒数.

可见time可以赋值给float类型
所以可以这样写:
float a = time;

这样就可以很容易的到两个时间点中间相差多少秒。
在 iOS 中使用 Objective - C 实现原生 Toast 并设置显示时长,有多种实现方式,以下分别介绍自定义视图和使用第三方库的方法。 ### 自定义 Toast 视图 通过自定义一个 `UIView` 作为 Toast 视图,然后添加到当前视图上,并设置显示时长。 ```objc #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self showToastWithMessage:@"这是一个 Toast 消息" duration:2.0]; } - (void)showToastWithMessage:(NSString *)message duration:(NSTimeInterval)duration { UIView *toastView = [[UIView alloc] init]; toastView.backgroundColor = [UIColor blackColor]; toastView.alpha = 0.8; toastView.layer.cornerRadius = 5; toastView.clipsToBounds = YES; UILabel *toastLabel = [[UILabel alloc] init]; toastLabel.text = message; toastLabel.textColor = [UIColor whiteColor]; toastLabel.textAlignment = NSTextAlignmentCenter; toastLabel.font = [UIFont systemFontOfSize:14]; [toastLabel sizeToFit]; toastView.frame = CGRectMake((self.view.bounds.size.width - toastLabel.bounds.size.width - 20) / 2, self.view.bounds.size.height - 100, toastLabel.bounds.size.width + 20, toastLabel.bounds.size.height + 20); toastLabel.frame = CGRectMake(10, 10, toastLabel.bounds.size.width, toastLabel.bounds.size.height); [toastView addSubview:toastLabel]; [self.view addSubview:toastView]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [toastView removeFromSuperview]; }); } @end ``` ### 使用第三方库 `MBProgressHUD` `MBProgressHUD` 是一个常用的第三方库,可以方便地实现 Toast 效果并设置显示时长。 首先,需要通过 CocoaPods 安装 `MBProgressHUD`: ```ruby pod 'MBProgressHUD' ``` 然后在代码中使用: ```objc #import "ViewController.h" #import "MBProgressHUD.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self showMBProgressHUDToastWithMessage:@"这是一个 Toast 消息" duration:2.0]; } - (void)showMBProgressHUDToastWithMessage:(NSString *)message duration:(NSTimeInterval)duration { MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; hud.mode = MBProgressHUDModeText; hud.label.text = message; [hud hideAnimated:YES afterDelay:duration]; } @end ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值