PS:工程中需单独添加 Masonry 第三方库
创建一个类,我这里类名ToastVC,继承自UIViewController
在.h文件中
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, ToastStatus) {
ToastStatus_Success,
ToastStatus_Error,
ToastStatus_Info,
};
@interface ToastVC : UIViewController
+ (void)toastWithTitle:(NSString *)title status:(ToastStatus)status owner:(UIViewController *)owner;
@end
在.m文件中
#import "ToastVC.h"
CGFloat statusBarHeight = 0.0;
@interface ToastVC ()
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) NSArray *colors;
@end
@implementation ToastVC
- (void)viewDidLoad {
[super viewDidLoad];
statusBarHeight = [UIApplication sharedApplication].windows.firstObject.windowScene.statusBarManager.statusBarFrame.size.height;
}
// 模仿QQ:顶部显示提示信息,1-2行,2秒自动消失
+ (void)toastWithTitle:(NSString *)title status:(ToastStatus)status owner:(UIViewController *)owner {
ToastVC *v = [[ToastVC alloc] init];
[[UIApplication sharedApplication].windows.firstObject addSubview:v.view];
[v.button setTitle:title forState:UIControlStateNormal];
v.view.backgroundColor = v.colors[status];
CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = statusBarHeight + owner.navigationController.navigationBar.frame.size.height;
v.view.frame = CGRectMake(0, -height, width, height);
[UIView animateWithDuration:0.3 animations:^{
v.view.frame = CGRectMake(0, 0, width, height);
}];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.3 animations:^{
v.view.frame = CGRectMake(0, -height, width, height);
} completion:^(BOOL finished) {
[v.view removeFromSuperview];
}];
});
}
#pragma mark - SET/GET
- (UIButton *)button {
if (_button == nil) {
_button = [UIButton buttonWithType:UIButtonTypeCustom];
_button.clipsToBounds = YES;
_button.layer.masksToBounds = YES;
[_button.titleLabel setNumberOfLines:2];
[_button.titleLabel setFont:[UIFont systemFontOfSize:16]];
[_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.view addSubview:_button];
[_button mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(statusBarHeight);
make.bottom.mas_equalTo(0);
make.left.mas_equalTo(8);
make.right.mas_equalTo(-8);
}];
}
return _button;
}
- (NSArray *)colors {
if (_colors == nil) {
_colors = @[[UIColor greenColor], [UIColor redColor], [UIColor orangeColor]];
}
return _colors;
}
@end
转载:https://blog.csdn.net/qq_16804091/article/details/106836600
查看评论