天天看點

Swift開發---toast 界面底部顯示的提示框

在這我直接介紹需要添加哪些代碼,可直接複制黏貼來使用。我是特意建立的 Tool.h Tool.m 來放oc代碼公用的方法,要是放在.swift就不用這麼麻煩了  可以直接使用。

1. 在  Tool.h  檔案中添加如下代碼:

//類似安卓提示框

+(void)showMessage:(NSString *)message  withFont:(CGFloat)font;

2.在 Tool.m 檔案中添加如下代碼:

#pragma mark -- 提示框

+(void)showMessage:(NSString *)message  withFont:(CGFloat)font

{

//    UIWindow * window = [UIApplication sharedApplication].keyWindow;

    UIWindow * window = [[UIApplication sharedApplication].windows objectAtIndex:1];

    UIView *showview =  [[UIView alloc]init];

    showview.backgroundColor = [UIColor blackColor];

    showview.frame = CGRectMake(1, 1, 1, 1);

    showview.alpha = 1.0f;

    showview.layer.cornerRadius = 5.0f;

    showview.layer.masksToBounds = YES;

    [window addSubview:showview];

    [window bringSubviewToFront:showview];

    UILabel *label = [[UILabel alloc]init];

    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:font+2] constrainedToSize:CGSizeMake(290, 9000)];

    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);

    label.text = message;

    label.textColor = [UIColor whiteColor];

    label.textAlignment = 1;

    label.backgroundColor = [UIColor clearColor];

    //    label.font = [UIFont boldSystemFontOfSize:font];//需要使用加粗字型文字可打開這行,注釋

    label.font = [UIFont systemFontOfSize:font];

    [showview addSubview:label];

    showview.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - LabelSize.width - 20)/2, [UIScreen mainScreen].bounds.size.height - 100, LabelSize.width+20, LabelSize.height+10);

    [UIView animateWithDuration:2 animations:^{

        showview.alpha = 0;

    } completion:^(BOOL finished) {

        [showview removeFromSuperview];

    }];

}

3.在别的viewcontroller.swift 調用的代碼如下:

Tool.showMessage("輸入你想要顯示的文字!", withFont: 15)