XZ_iOS之自定义2秒钟自动消失的提示框
项目中有的时候需要几秒钟就自动消失的提示框,使用第三方的发现适配不行,于是,我自己写了一个
XZAutoHideAlertView.m
#import"XZAutoHideAlertView.h"
@implementation XZAutoHideAlertView
void ShowAutoHideAlertView(NSString
*labelText)
{
if
([labelTextlength] <=0)
return;
[[XZAutoHideAlertViewalloc]initWithText:labelText];
}
- (void)initWithText:(NSString
*)text {
if
(self == [superinit])
{
[selfsetUpAutoHideAlertView:text];
}
}
- (void)setUpAutoHideAlertView:(NSString
*)text {
UIWindow
*window = [UIApplicationsharedApplication].keyWindow;
[windowaddSubview:self];
CGFloat
kScreenWidth = [UIScreenmainScreen].bounds.size.width;
CGFloat
width = kScreenWidth - (100 /
375.0 * kScreenWidth);
CGFloat
height = [selfgetStringCGSizeWithMaxSize:CGSizeMake(width,MAXFLOAT)WithFont:[UIFontsystemFontOfSize:15.0f]text:text].height
+ 20;
if
(height <50) {
height =50;
}
UILabel
*labelAlert = [[UILabelalloc]initWithFrame:CGRectMake(0,0,
width, height)];
[selfaddSubview:labelAlert];
labelAlert.center
= window.center;
labelAlert.numberOfLines
= 0;
labelAlert.textAlignment
= NSTextAlignmentCenter;
labelAlert.font
= [UIFontsystemFontOfSize:15.0f];
labelAlert.textColor
= [UIColorwhiteColor];
labelAlert.backgroundColor
= [UIColorblackColor];
labelAlert.layer.masksToBounds
= YES;
labelAlert.layer.cornerRadius
= 5.0;
labelAlert.alpha
= 0.9;
labelAlert.text
= text;
[selfperformSelector:@selector(hideDelayed)withObject:[NSNumbernumberWithBool:YES]afterDelay:2.0];
}
- (void)hideDelayed
{
[selfremoveFromSuperview];
}
- (CGSize)getStringCGSizeWithMaxSize:(CGSize)maxSize
WithFont:(UIFont *)font text:(NSString
*)text
{
NSDictionary
*attres =@{NSFontAttributeName:font};
return
[textboundingRectWithSize:maxSizeoptions:NSStringDrawingUsesLineFragmentOrigin
| NSStringDrawingUsesFontLeadingattributes:attrescontext:nil].size;
}
@end
XZAutoHideAlertView.h
#import<UIKit/UIKit.h>
@interface XZAutoHideAlertView :UIView
void ShowAutoHideAlertView(NSString
*labelText);
@end
// 调用方法
ShowAutoHideAlertView(@“我是一个提示框”);