在iOS中ToastView封裝

這里使用的是OC的代碼封裝的
.h里面聲明好接口


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#define TOAST_LONG  2000
#define TOAST_SHORT 1000

#define kCBToastPadding         20
#define kCBToastMaxWidth        220
#define kCBToastCornerRadius    5.0
#define kCBToastFadeDuration    0.5
#define kCBToastTextColor       [UIColor whiteColor]
#define kCBToastBottomPadding   30

@interface ToastView : NSObject

+ (void)showToast:(NSString *)message withDuration:(NSUInteger)duration;

/**
 * 含有圖片的信息提示
 *?
 *  1:表示ok
 *  0:表示warn
 */
+ (void)showToast:(NSString *)message imgType:(NSInteger)type withDuration:(NSUInteger)duration;

+ (void)dismissToast;

@end

.m里面實(shí)現(xiàn)方法


#import "ToastView.h"

#define FLT_APP_WINDOW  [[UIApplication sharedApplication] keyWindow]

@implementation ToastView

+ (void)showToast:(NSString *)message withDuration:(NSUInteger)duration {
    [ToastView dismissToast];
    dispatch_async(dispatch_get_main_queue(), ^{
        // build the toast label
        UILabel *toast = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        toast.text = message;
        toast.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.6f];
        toast.textColor = kCBToastTextColor;
        toast.numberOfLines = 1000;
        toast.tag = 1024;
        toast.textAlignment = NSTextAlignmentCenter;
        toast.lineBreakMode = NSLineBreakByWordWrapping;
        toast.font = [UIFont systemFontOfSize:14.0f];
        toast.layer.cornerRadius = kCBToastCornerRadius;
        toast.layer.masksToBounds = YES;

        // resize based on message
        CGSize maximumLabelSize = CGSizeMake(kCBToastMaxWidth, 9999);
        CGSize expectedLabelSize = [toast.text boundingRectWithSize:maximumLabelSize
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName:toast.font}
                                                            context:nil].size;
        //adjust the label to the new height
        CGRect newFrame = toast.frame;
        newFrame.size = CGSizeMake(expectedLabelSize.width + kCBToastPadding,
                                   expectedLabelSize.height + kCBToastPadding);
        toast.frame = newFrame;

        // add the toast to the root window (so it overlays everything)
        if ([toast.text length] > 0) {
            [FLT_APP_WINDOW addSubview:toast];

            // get the window frame to determine placement
            CGRect windowFrame = FLT_APP_WINDOW.frame;

            // align the toast properly
            toast.center = CGPointMake(windowFrame.size.width / 2, windowFrame.size.height / 2);

            // round the x/y coords so they aren't 'split' between values (would appear blurry)
            toast.frame = CGRectMake(round(toast.frame.origin.x),
                                     round(toast.frame.origin.y),
                                     toast.frame.size.width,
                                     toast.frame.size.height);

            // set up the fade-in
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:kCBToastFadeDuration];

            // values being aninmated
            toast.alpha = 1.0f;

            // perform the animation
            [UIView commitAnimations];

            // calculate the delay based on fade-in time + display duration
            NSTimeInterval delay = duration;

            // set up the fade out (to be performed at a later time)
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDelay:delay];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            [UIView setAnimationDelegate:toast];
            [UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];

            // values being animated
            toast.alpha = 0.0f;

            // commit the animation for being performed when the timer fires
            [UIView commitAnimations];
        }
    });
}

+ (void)showToast:(NSString *)message imgType:(NSInteger)type withDuration:(NSUInteger)duration {
    [ToastView dismissToast];// 加上這句話避免重復(fù)點(diǎn)擊時(shí)出現(xiàn)疊加
    dispatch_async(dispatch_get_main_queue(), ^{
        // build the toast label
        UIView *toastView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40,40)];
        toastView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.6f];;
        toastView.layer.cornerRadius = kCBToastCornerRadius;
        toastView.layer.masksToBounds = YES;
        toastView.tag = 1024;

        // 圖片添加
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(kCBToastPadding/2, kCBToastPadding/2, 15, 15)];
        if (type == 0) {
            imageview.image = [UIImage imageNamed:@"alert_warn"];
        } else {
            imageview.image = [UIImage imageNamed:@"alert_ok"];
        }
        [toastView addSubview:imageview];

        // label添加
        UILabel *toast = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        toast.backgroundColor = [UIColor clearColor];
        toast.text = message;
        toast.textColor = kCBToastTextColor;
        toast.numberOfLines = 1000;
        toast.textAlignment = NSTextAlignmentCenter;
        toast.lineBreakMode = NSLineBreakByWordWrapping;
        toast.font = [UIFont systemFontOfSize:14.0f];

        // resize based on message
        CGSize maximumLabelSize = CGSizeMake(kCBToastMaxWidth, 9999);
        CGSize expectedLabelSize = [toast.text boundingRectWithSize:maximumLabelSize
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName:toast.font}
                                                            context:nil].size;
        //        //adjust the label to the new height
        toast.frame = CGRectMake(kCBToastPadding+15, kCBToastPadding/2 - 1.5, expectedLabelSize.width, expectedLabelSize.height);
        toastView.frame = CGRectMake(0, 0, expectedLabelSize.width+kCBToastPadding*1.5+15, expectedLabelSize.height+kCBToastPadding);

 [toastView addSubview:toast];

        // add the toast to the root window (so it overlays everything)
        if ([message length] > 0) {
            [FLT_APP_WINDOW addSubview:toastView];

            // get the window frame to determine placement
            CGRect windowFrame = FLT_APP_WINDOW.frame;

            // align the toast properly
            toastView.center = CGPointMake(windowFrame.size.width / 2, windowFrame.size.height / 2);

            // round the x/y coords so they aren't 'split' between values (would appear blurry)
            toastView.frame = CGRectMake(round(toastView.frame.origin.x),
                                         round(toastView.frame.origin.y),
                                         toastView.frame.size.width,
                                         toastView.frame.size.height);

            // set up the fade-in
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:kCBToastFadeDuration];

            // values being aninmated
            toastView.alpha = 1.0f;

            // perform the animation
            [UIView commitAnimations];

            // calculate the delay based on fade-in time + display duration
            NSTimeInterval delay = duration;

            // set up the fade out (to be performed at a later time)
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDelay:delay];
            [UIView setAnimationDuration:kCBToastFadeDuration];
            [UIView setAnimationDelegate:toastView];
            [UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];

            // values being animated
            toastView.alpha = 0.0f;

            // commit the animation for being performed when the timer fires
            [UIView commitAnimations];
        }
    });
}

+ (void)dismissToast {
    UIView *toast = (UIView *)FLT_APP_WINDOW.subviews.lastObject;

    if (toast.tag == 1024) {
        [toast removeFromSuperview];
    }
}

@end

調(diào)用處代碼

- (IBAction)normal:(id)sender {
    [ToastView showToast:@"很普通的toastView" withDuration:10.0];
}
- (IBAction)ok:(id)sender {
    [ToastView showToast:@"提示圖片帶有OK" imgType:0 withDuration:10.0];
}
- (IBAction)warn:(id)sender {
    [ToastView showToast:@"提示圖片帶有警告" imgType:1 withDuration:10.0];
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末搬卒,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌乡数,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件窖壕,死亡現(xiàn)場(chǎng)離奇詭異超歌,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)悯衬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人筋粗,你說(shuō)我怎么就攤上這事策橘。” “怎么了娜亿?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵丽已,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我买决,道長(zhǎng)沛婴,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任督赤,我火速辦了婚禮嘁灯,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘躲舌。我一直安慰自己丑婿,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布没卸。 她就那樣靜靜地躺著羹奉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪约计。 梳的紋絲不亂的頭發(fā)上诀拭,一...
    開(kāi)封第一講書(shū)人閱讀 51,258評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音煤蚌,去河邊找鬼耕挨。 笑死,一個(gè)胖子當(dāng)著我的面吹牛铺然,可吹牛的內(nèi)容都是我干的俗孝。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼魄健,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼赋铝!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起沽瘦,我...
    開(kāi)封第一講書(shū)人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤革骨,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后析恋,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體良哲,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年助隧,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了筑凫。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖巍实,靈堂內(nèi)的尸體忽然破棺而出滓技,到底是詐尸還是另有隱情,我是刑警寧澤棚潦,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布令漂,位于F島的核電站,受9級(jí)特大地震影響丸边,放射性物質(zhì)發(fā)生泄漏叠必。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一妹窖、第九天 我趴在偏房一處隱蔽的房頂上張望纬朝。 院中可真熱鬧,春花似錦嘱吗、人聲如沸玄组。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至哆致,卻和暖如春绕德,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背摊阀。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工耻蛇, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人胞此。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓臣咖,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親漱牵。 傳聞我的和親對(duì)象是個(gè)殘疾皇子夺蛇,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,093評(píng)論 25 707
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件酣胀、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,098評(píng)論 4 62
  • 新文禮是排名第十一的隋唐好漢刁赦,他和排名第十的好漢尚師徒,排名只相差一名闻镶。 然而甚脉,新文禮和尚師徒兩人,在《說(shuō)唐》中的...
    章雪峰閱讀 846評(píng)論 0 5
  • 文/ Kurny 冷冷的冰雨已經(jīng)偃旗息鼓 涼風(fēng)撥走了遮天蔽日的烏云 陽(yáng)光重又溫暖照耀人間 在朱紅色的墻上 在沉睡未...
    Kurny91閱讀 407評(píng)論 2 3
  • 青巖寺坐落在遼寧省北鎮(zhèn)市铆农,跟其它名山名寺比起來(lái)似乎略遜一籌牺氨,但在東北,絕對(duì)是最知名的,可謂家喻戶曉猴凹。 據(jù)說(shuō)青巖寺的...
    孤煙3936閱讀 7,525評(píng)論 0 1