iOS實現android的toast效果

代碼如下:

//
//
//  Created by Bigun on 2019/7/2.
//  Copyright © 2019 Enjoy. All rights reserved.
//

#import "HNToastView.h"

@implementation HNToastView
+(void)toast:(NSString*)text{
    if (![text length]){
        text = @"發生未知錯誤";
    }
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    // 延時1s執行toast
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        UILabel *_label = [[UILabel alloc] init];
        _label.text = text;
        _label.tag = 1001;
        _label.textAlignment = NSTextAlignmentCenter;
        _label.layer.cornerRadius = 18.f;
        _label.font = [UIFont systemFontOfSize:14];
        _label.layer.masksToBounds = YES;
        // 根據字體得到NSString的尺寸
        CGSize size = [_label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:_label.font,NSFontAttributeName,nil]];
        _label.frame = CGRectMake(100,100, size.width,size.height);
        _label.textColor = [UIColor whiteColor];
        _label.backgroundColor = [UIColor blackColor];
        _label.alpha = 0.8;
        _label.translatesAutoresizingMaskIntoConstraints = NO;
        
        [[UIApplication sharedApplication].keyWindow addSubview:_label];

        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(size.width+50, size.height+20));
            make.centerX.equalTo(_label.superview);
            make.bottom.equalTo(_label.superview).offset(-150);
        }];
        
        [UIView animateWithDuration:3 animations:^{
            _label.alpha = 0;
        }];
    });
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    UIView *view = [self getViewByTag:1001 andParentView:[UIApplication sharedApplication].keyWindow];
    if (view){
        [view removeFromSuperview];
        view = nil;
    }
}

-(UIView*)getViewByTag:(int)tag andParentView:(UIView*)parentView{
    for (UIView *findView in parentView.subviews){
        if (findView.tag == tag){
            return findView;
        }
    }
    return nil;
}
@end

調用方法
[HNToastView toast:@“xxx”];

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章