UIView+Toast.m 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #import "UIView+Toast.h"
  2. @implementation UIView (Toast)
  3. - (void)showToast:(NSString *)message {
  4. [self showToast:message duration:2.0];
  5. }
  6. - (void)showToast:(NSString *)message duration:(NSTimeInterval)duration {
  7. if (!message || message.length == 0) {
  8. return;
  9. }
  10. // 创建toast容器
  11. UIView *toastContainer = [[UIView alloc] init];
  12. toastContainer.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.8];
  13. toastContainer.layer.cornerRadius = 8;
  14. toastContainer.clipsToBounds = YES;
  15. // 创建文字标签
  16. UILabel *toastLabel = [[UILabel alloc] init];
  17. toastLabel.text = message;
  18. toastLabel.textColor = [UIColor whiteColor];
  19. toastLabel.font = [UIFont systemFontOfSize:(16)];
  20. toastLabel.textAlignment = NSTextAlignmentCenter;
  21. toastLabel.numberOfLines = 1;
  22. [toastContainer addSubview:toastLabel];
  23. // 添加到当前视图
  24. [self addSubview:toastContainer];
  25. // 计算文字大小
  26. CGSize textSize = [message boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - (30), CGFLOAT_MAX)
  27. options:NSStringDrawingUsesLineFragmentOrigin
  28. attributes:@{NSFontAttributeName: toastLabel.font}
  29. context:nil].size;
  30. // 设置容器约束
  31. [toastContainer mas_makeConstraints:^(MASConstraintMaker *make) {
  32. make.centerX.mas_offset(0);
  33. make.centerY.mas_offset(0);
  34. make.width.mas_equalTo(textSize.width + (40));
  35. make.height.mas_equalTo(textSize.height + (20));
  36. }];
  37. // 设置文字约束
  38. [toastLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  39. make.center.equalTo(toastContainer);
  40. }];
  41. // 初始状态
  42. toastContainer.alpha = 0.0;
  43. toastContainer.transform = CGAffineTransformMakeScale(0.8, 0.8);
  44. // 显示动画
  45. [UIView animateWithDuration:0.3 animations:^{
  46. toastContainer.alpha = 1.0;
  47. toastContainer.transform = CGAffineTransformIdentity;
  48. } completion:^(BOOL finished) {
  49. // 延迟隐藏
  50. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  51. [UIView animateWithDuration:0.3 animations:^{
  52. toastContainer.alpha = 0.0;
  53. toastContainer.transform = CGAffineTransformMakeScale(0.8, 0.8);
  54. } completion:^(BOOL finished) {
  55. [toastContainer removeFromSuperview];
  56. }];
  57. });
  58. }];
  59. }
  60. @end