您的位置:首页 > 其它

自定义类似于安卓中的Toast控件

2015-07-17 17:36 253 查看

主要通过类目,就可以在整个项目中使用

#import "UIViewController+ToastView.h"

@implementation UIViewController (ToastView)

//用单例 避免多次点击时  出现Toast叠加的现象

+(UILabel *)label{

    static UILabel *label;

    static dispatch_once_t once;

    dispatch_once(&once, ^{

        label = [[UILabel alloc] init];

        label.font = [UIFont systemFontOfSize:20];

    });

    return label;

}

-(void)toast:(NSString *)text length:(ToastTime)length{

   

    UILabel *lab =[[self class] label];

   //动态获取length在labe中的长度和高度    attibutes是字体

    CGRect rect = [text boundingRectWithSize:CGSizeMake(kWidth-100, MAXFLOAT) 

                                                             options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin) 

                                                          attributes:@{NSFontAttributeName:lab.font}

                                                             context:nil];

   

    NSLog(@"%@",NSStringFromCGRect(rect));

   

    CGRect frame = lab.frame;

//将字符串的长度,赋值给lable

       frame.size =  CGSizeMake(rect.size.width, rect.size.height+40);

       lab.numberOfLines = 0;

      lab.frame = frame;

      lab.textAlignment = NSTextAlignmentCenter;

   

      lab.text = text;

      lab.center = CGPointMake(kWidth/2, kHeight/2);

      lab.textColor = [UIColor whiteColor];

      lab.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.7];

      [self.view addSubview:lab];

//消失的时间   最长5秒消失

      length = length < 5 ? length :5;

   

//    if(length < ){

//Toast消失

        [self performSelector:@selector(remove:) withObject:lab afterDelay:length];

//    }

//    else{

//        [self performSelector:@selector(remove:) withObject:lab afterDelay:ToastLong];

//    }

   

}

-(void)remove:(UIView *)view{

    [view removeFromSuperview];

}

@end

将-(void)toast:(NSString *)text length:(ToastTime)length这个方法在其.h文件中声明

使用:在任意一个viewcontroller中调用  如:

 [self toast:@"司法局收电带你飞" length:2];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息