iPhoneでToastを表示する方法
Androidでは、アプリからユーザに対して、ちょっとした情報を提示するためにToastが用意されています。
しかし、iPhoneではToastに該当するものが用意されていません。
なので、iPhoneでToastのようなものを表示したい場合は、開発者が自前で準備してやる必要があります。
今回はその方法をご紹介します。
方法の概要としては、UIButtonをベースにToastぽいものを作成します。
以下にサンプルコードを記載します。
(サンプルなのでメモリ効率などは考慮していません)
#import <UIKit/UIKit.h> @interface Toast : UIButton -(void)initWithMessage:(NSString *)msg showTime:(float)sec parentView:(UIView *)parentview; -(void)tapToast; @end
#import <QuartzCore/QuartzCore.h> #import "Toast.h" @implementation Toast -(void)initWithMessage:(NSString *)msg showTime:(float)sec parentView:(UIView *)parentview{ UIFont *font = [UIFont systemFontOfSize:14]; CGSize textSize = [msg sizeWithFont:font constrainedToSize:CGSizeMake(300, 50)]; //ラベルの生成 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, textSize.width + 5, textSize.height + 5)]; label.backgroundColor = [UIColor clearColor]; label.textColor = [UIColor whiteColor]; label.font = font; label.text = msg; label.numberOfLines = 0; label.shadowColor = [UIColor darkGrayColor]; label.shadowOffset = CGSizeMake(1, 1); // toast として使うボタンの生成 self = [Toast buttonWithType:UIButtonTypeCustom]; self.frame = CGRectMake(0, 0, textSize.width + 10, textSize.height + 10); label.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2); // label をボタンに登録する [self addSubview:label]; //背景色の設定 self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7]; //角を丸くする設定 [[self layer] setCornerRadius:10.0]; [self setClipsToBounds:YES]; CGPoint point = CGPointMake(parentview.frame.size.width/2, parentview.frame.size.height/2); point = CGPointMake(parentview.frame.size.width / 2, parentview.frame.size.height - 60); point = CGPointMake(point.x, point.y); self.center = point; //トーストがタップされた場合は非表示にする [self addTarget:self action:@selector(tapToast) forControlEvents: UIControlEventTouchDown]; //親画面に追加する [parentview addSubview:self]; //タイマーにより自動的に非表示にする [NSTimer scheduledTimerWithTimeInterval:sec target:self selector:@selector(tapToast) userInfo:nil repeats:NO]; } -(void)tapToast{ self.hidden = YES; self = nil; } @end
※「#import
#import "ViewController.h" #import "Toast.h" @implementation ViewController -(IBAction)tapButton{ //「トースト」と1.5秒間表示される [[Toast alloc] initWithMessage:@"トースト" showTime:1.5 parentView:self.view]; } //中略 @end
Toastを表示したいときは、上記の様に1行で記述することができます。
執筆者:中の人A