#import "UIView+Toast.h" @implementation UIView (Toast) - (void)showToast:(NSString *)message { [self showToast:message duration:2.0]; } - (void)showToast:(NSString *)message duration:(NSTimeInterval)duration { if (!message || message.length == 0) { return; } // 创建toast容器 UIView *toastContainer = [[UIView alloc] init]; toastContainer.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.8]; toastContainer.layer.cornerRadius = 8; toastContainer.clipsToBounds = YES; // 创建文字标签 UILabel *toastLabel = [[UILabel alloc] init]; toastLabel.text = message; toastLabel.textColor = [UIColor whiteColor]; toastLabel.font = [UIFont systemFontOfSize:(16)]; toastLabel.textAlignment = NSTextAlignmentCenter; toastLabel.numberOfLines = 1; [toastContainer addSubview:toastLabel]; // 添加到当前视图 [self addSubview:toastContainer]; // 计算文字大小 CGSize textSize = [message boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - (30), CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: toastLabel.font} context:nil].size; // 设置容器约束 [toastContainer mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.mas_offset(0); make.centerY.mas_offset(0); make.width.mas_equalTo(textSize.width + (40)); make.height.mas_equalTo(textSize.height + (20)); }]; // 设置文字约束 [toastLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.center.equalTo(toastContainer); }]; // 初始状态 toastContainer.alpha = 0.0; toastContainer.transform = CGAffineTransformMakeScale(0.8, 0.8); // 显示动画 [UIView animateWithDuration:0.3 animations:^{ toastContainer.alpha = 1.0; toastContainer.transform = CGAffineTransformIdentity; } completion:^(BOOL finished) { // 延迟隐藏 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [UIView animateWithDuration:0.3 animations:^{ toastContainer.alpha = 0.0; toastContainer.transform = CGAffineTransformMakeScale(0.8, 0.8); } completion:^(BOOL finished) { [toastContainer removeFromSuperview]; }]; }); }]; } @end