iOS自定义alertView提示框

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

iOS UIKit框架下自带的UIAlertView在功能或者美观上,有的时候并不能满足我们的开发需求,这个时候,就可以自定义alertView。我在这里写了一个简单的自定义alertView的Demo,希望能帮助到iOS开发的小伙们。话不多说,直接上代码:

在。h里:

#import <UIKit/UIKit.h>

typedef void(^alertClick)(NSInteger index);

@interface SLAlertView : UIView
@property (nonatomic,copy) alertClick clickIndex;

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message sureBtn:(NSString *)sureTitle cancleBtn:(NSString *)cancleTitle;

- (void)show;

@end


在。m里:

#import "SLAlertView.h"
#define alertViewWidth 280 //alertView 宽
#define edge 10.0 //各个栏目之间的距离

@interface SLAlertView ()
@property (nonatomic,retain) UIView *alertView;//弹窗
@property (nonatomic,retain) UILabel *titleLbl;//title
@property (nonatomic,retain) UILabel *msgLbl;//内容
@property (nonatomic,retain) UIButton *sureBtn;//确认按钮
@property (nonatomic,retain) UIButton *cancleBtn;//取消按钮
@property (nonatomic,retain) UIView *lineView;//横线线
@property (nonatomic,retain) UIView *verLineView;//竖线
@end

@implementation SLAlertView

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message sureBtn:(NSString *)sureTitle cancleBtn:(NSString *)cancleTitle
{
    if (self == [super init]) {
        
        self.frame = [UIScreen mainScreen].bounds;
        
        self.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
        
        self.alertView = [[UIView alloc] init];
        self.alertView.backgroundColor = [UIColor whiteColor];
        self.alertView.layer.cornerRadius = 8.0;
        
        self.alertView.frame = CGRectMake(0, 0, alertViewWidth, 100);
        self.alertView.layer.position = self.center;
        
        if (title) {
            
            self.titleLbl = [self GetAdaptiveLable:CGRectMake(2*edge, 2*edge, alertViewWidth-4*edge, 20) AndText:title andIsTitle:YES];
            self.titleLbl.textAlignment = NSTextAlignmentCenter;
            
            [self.alertView addSubview:self.titleLbl];
            
            CGFloat titleW = self.titleLbl.bounds.size.width;
            CGFloat titleH = self.titleLbl.bounds.size.height;
            
            self.titleLbl.frame = CGRectMake((alertViewWidth-titleW)/2, 2*edge, titleW, titleH);
            
        }
        if (message) {
            
            self.msgLbl = [self GetAdaptiveLable:CGRectMake(edge, CGRectGetMaxY(self.titleLbl.frame)+edge, alertViewWidth-2*edge, 20) AndText:message andIsTitle:NO];
            self.msgLbl.textAlignment = NSTextAlignmentCenter;
            
            [self.alertView addSubview:self.msgLbl];
            
            CGFloat msgW = self.msgLbl.bounds.size.width;
            CGFloat msgH = self.msgLbl.bounds.size.height;
            
            self.msgLbl.frame = self.titleLbl?CGRectMake((alertViewWidth-msgW)/2, CGRectGetMaxY(self.titleLbl.frame)+edge, msgW, msgH):CGRectMake((alertViewWidth-msgW)/2, 2*edge, msgW, msgH);
        }
        
        self.lineView = [[UIView alloc] init];
        self.lineView.frame = self.msgLbl?CGRectMake(0, CGRectGetMaxY(self.msgLbl.frame)+2*edge, alertViewWidth, 1):CGRectMake(0, CGRectGetMaxY(self.titleLbl.frame)+2*edge, alertViewWidth, 1);
        self.lineView.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
        [self.alertView addSubview:self.lineView];
        
        //两个按钮
        if (cancleTitle && sureTitle) {
            
            self.cancleBtn = [UIButton buttonWithType:UIButtonTypeSystem];
            self.cancleBtn.frame = CGRectMake(0, CGRectGetMaxY(self.lineView.frame), (alertViewWidth-1)/2, 40);
            [self.cancleBtn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.2]] forState:UIControlStateNormal];
            [self.cancleBtn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.2]] forState:UIControlStateSelected];
            [self.cancleBtn setTitle:cancleTitle forState:UIControlStateNormal];
            //[self.cancleBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            self.cancleBtn.tag = 1;
            [self.cancleBtn addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
            
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.cancleBtn.bounds byRoundingCorners:UIRectCornerBottomLeft cornerRadii:CGSizeMake(5.0, 5.0)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = self.cancleBtn.bounds;
            maskLayer.path = maskPath.CGPath;
            self.cancleBtn.layer.mask = maskLayer;
            
            [self.alertView addSubview:self.cancleBtn];
        }
        
        if (cancleTitle && sureTitle) {
            self.verLineView = [[UIView alloc] init];
            self.verLineView.frame = CGRectMake(CGRectGetMaxX(self.cancleBtn.frame), CGRectGetMaxY(self.lineView.frame), 1, 40);
            self.verLineView.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
            [self.alertView addSubview:self.verLineView];
        }
        
        if(sureTitle && cancleTitle){
            
            self.sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
            self.sureBtn.frame = CGRectMake(CGRectGetMaxX(self.verLineView.frame), CGRectGetMaxY(self.lineView.frame), (alertViewWidth-1)/2+1, 40);
            [self.sureBtn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.2]] forState:UIControlStateNormal];
            [self.sureBtn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.2]] forState:UIControlStateSelected];
            [self.sureBtn setTitle:sureTitle forState:UIControlStateNormal];
            //[self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            self.sureBtn.tag = 2;
            [self.sureBtn addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
            
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.sureBtn.bounds byRoundingCorners:UIRectCornerBottomRight cornerRadii:CGSizeMake(5.0, 5.0)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = self.sureBtn.bounds;
            maskLayer.path = maskPath.CGPath;
            self.sureBtn.layer.mask = maskLayer;
            
            [self.alertView addSubview:self.sureBtn];
            
        }
        
        //只有取消按钮
        if (cancleTitle && !sureTitle) {
            
            self.cancleBtn = [UIButton buttonWithType:UIButtonTypeSystem];
            self.cancleBtn.frame = CGRectMake(0, CGRectGetMaxY(self.lineView.frame), alertViewWidth, 40);
            [self.cancleBtn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.2]] forState:UIControlStateNormal];
            [self.cancleBtn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.2]] forState:UIControlStateSelected];
            [self.cancleBtn setTitle:cancleTitle forState:UIControlStateNormal];
            //[self.cancleBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            self.cancleBtn.tag = 1;
            [self.cancleBtn addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
            
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.cancleBtn.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(5.0, 5.0)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = self.cancleBtn.bounds;
            maskLayer.path = maskPath.CGPath;
            self.cancleBtn.layer.mask = maskLayer;
            
            [self.alertView addSubview:self.cancleBtn];
        }
        
        //只有确定按钮
        if(sureTitle && !cancleTitle){
            
            self.sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
            self.sureBtn.frame = CGRectMake(0, CGRectGetMaxY(self.lineView.frame), alertViewWidth, 40);
            [self.sureBtn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.2]] forState:UIControlStateNormal];
            [self.sureBtn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.2]] forState:UIControlStateSelected];
            [self.sureBtn setTitle:sureTitle forState:UIControlStateNormal];
            //[self.sureBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            self.sureBtn.tag = 2;
            [self.sureBtn addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
            
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.sureBtn.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(5.0, 5.0)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = self.sureBtn.bounds;
            maskLayer.path = maskPath.CGPath;
            self.sureBtn.layer.mask = maskLayer;
            
            [self.alertView addSubview:self.sureBtn];
            
        }
        
        //计算高度
        CGFloat alertHeight = cancleTitle?CGRectGetMaxY(self.cancleBtn.frame):CGRectGetMaxY(self.sureBtn.frame);
        self.alertView.frame = CGRectMake(0, 0, alertViewWidth, alertHeight);
        self.alertView.layer.position = self.center;
        
        [self addSubview:self.alertView];
    }
    
    return self;
}

//alertView弹出展示
- (void)show{

    //iOS8之后,[UIApplicationsharedApplication].windows有两个,第一个为UIWindow,是程序主要的keyWindow;第二个为UITextEffectsWindow,是键盘所在的window,当我们要覆盖住键盘时得在这个window上addSubview。

    [[[UIApplication sharedApplication].windows lastObject] addSubview:self];
    [self showAnimation];
}

#pragma mark - Animation  提示框弹出时的动画效果

- (void)showAnimation {
    CAKeyframeAnimation *alertViewshowAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    alertViewshowAnimation .duration = 0.4;
    alertViewshowAnimation .values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                                       [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                                       [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 1.0f)],
                                       [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    alertViewshowAnimation.keyTimes = @[@0.2f, @0.5f, @0.75f, @1.0f];
    alertViewshowAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                               [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                               [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [_alertView.layer addAnimation:alertViewshowAnimation forKey:nil];
}

#pragma mark - alertView按钮点击回调 
- (void)buttonEvent:(UIButton *)sender
{
    if (sender.tag == 2) {
        if (self.clickIndex) {
            self.clickIndex(sender.tag);
        }
   
    [self removeFromSuperview];
}

//子视图的创建和布局
-(UILabel *)GetAdaptiveLable:(CGRect)rect AndText:(NSString *)contentStr andIsTitle:(BOOL)isTitle
{
    UILabel *contentLbl = [[UILabel alloc] initWithFrame:rect];
    contentLbl.numberOfLines = 0;
    contentLbl.text = contentStr;
    contentLbl.textAlignment = NSTextAlignmentCenter;
    if (isTitle) {
        contentLbl.font = [UIFont boldSystemFontOfSize:16.0];
    }else{
        contentLbl.font = [UIFont systemFontOfSize:14.0];
    }
    
    NSMutableAttributedString *mAttrStr = [[NSMutableAttributedString alloc] initWithString:contentStr];
    NSMutableParagraphStyle *mParaStyle = [[NSMutableParagraphStyle alloc] init];
    mParaStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [mParaStyle setLineSpacing:3.0];
    [mAttrStr addAttribute:NSParagraphStyleAttributeName value:mParaStyle range:NSMakeRange(0,[contentStr length])];
    [contentLbl setAttributedText:mAttrStr];
    [contentLbl sizeToFit];
    
    return contentLbl;
}

//设置颜色
-(UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

@end

在你需要显示alert的时候:

SLAlertView *alert = [[SLAlertView alloc]initWithTitle:@"!!!" message:@"确定要删除吗?" sureBtn:@"我意已决" cancleBtn:@"我在想想"];

//点击按钮之后的回调

alert.resultIndex = ^(NSInteger index){
            NSLog(@"%d",index);
        };

[alert show];

以上就是自定义的一个简单的demo,你可以参照该demo,在此基础上进行修改,以达到你要的效果。


iOS自定义AlertView 简单易用、可定制AlertView;Powerful, Easy to use alert view or popup view on controller and window,custom view and animation,for swift,support iphone, ipad 立即下载

相关推荐

swift-快速实现自定义alertView

快速实现自定义alertView

IOS 自定义控件之UIAlertview

原创Blog,转载请注明出处 blog.csdn.net/hello_hwc前言:这个系列的目的是写一些自定义控件的思路,并不是拿来就可以用的控件,想要直接用的控件库,去github上有的是。这个系列希望抛砖引玉,能够让读者学会如何去自定义控件,授之以渔总比授之以鱼强。本文的内容 demo展示以及说明 如何自定义一个alertview 希望通过本文,读者能够学到 自定义控件的UI布局 自定义

Leo的专栏 5632

ios自定义alertview之模型一

自定义alertview,一款封装好的自定义alertview控件,多样化alertview使用

iOS-自定义HZAlertView

HZAlertView An easy way to use PUSH-ALERT-VIEW 自定义AlertView展示,和其他的几种展现方式(纯手工打造) 用法简单的alert框架:一行代码搞定 效果图 如何使用HZAlertView 使用之前请添加代理[HZAlertViewDelegate] 测试文本消息 NSString * texts = @"国际在线专稿为了赢得比赛和价值2...

whuizhou的专栏 619

iOS开发——自定义AlertView

  自定义AlertView,可以选择出现的动画方式,正文信息高度自动变化,特意做了几个可以对比。没啥难点,直接上代码,一看就懂。   1.在YYTAlertView.h文件中 // // YYTAlertView.h // Demo-自定义alertView // // Created by yyt on 16/4/19. // Copyright © 2016年 y...

weixin_30325487的博客 208

iOS-自定义Alert框

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34124577的博客 295

php使用自定义alert,IOS_iOS自定义alertView提示框实例分享,本文实例为大家分享iOS自定义a - phpStudy...

iOS自定义alertView提示框实例分享本文实例为大家分享iOS自定义alertView提示框,先上图,弹框的背景色,按钮背景色,提示的消息的字体颜色都可以改变利用单例实现丰富的自定义接口//// PBAlertController.h// PBAlertDemo//// Created by 裴波波 on 16/4/20.// Copyright © 2016年 裴波波. All right...

weixin_32533375的博客 179

iOS 7以后自定义UIAlertview(CustomIOS7AlertView)的用法

公司项目要求更新的提示框上要加明更新的内容,如下图所示: 但是用系统自带的UIAlertview 却偏偏成为了这个样子!   不对称很难看有木有! 故从网上搜寻如何能使message的text左对齐 找到如下:http://blog.csdn.net/andypan1314/article/details/8246407

u012076614的博客 710

关于iOS 7以后自定义UIAlertview(CustomIOS7AlertView)的用法心得

公司项目要求更新的提示框上要加明更新的内容,如下图所示: 但是用系统自带的UIAlertview 却偏偏成为了这个样子! 不对称很难看有木有! 故从网上搜寻如何能使message的text左对齐 找到如下:http://blog.csdn.net/andypan1314/article/details/8246407 经调试,发现根本在iOS 8 上不起作...

weixin_30415801的博客 85

自消alertView

#pragma mark - 自消alertView - (void)showDissmissSelfAlertViewTitle:(NSString *)aTitle message:(NSString *)aMessage complete:(void (^)(void))complete {     doneBlock = complete;     if (aTitle == n

lxm_780337的博客 287

可自己消失的alterView

#pragma mark - 自消alertView - (void)showDissmissSelfAlertViewTitle:(NSString *)aTitle message:(NSString *)aMessage complete:(void (^)(void))complete {     doneBlock = complete;     if (aTitle == n

lxm_780337的博客 408

iOS自定义提示弹出框实现类似UIAlertView的效果

最近在学习iOS开发,在牛刀小试的时候发现系统的UIAlertView有点不喜欢,然后就自己自定义一个UIAlertView,基本上实现了系统的UIAlertView,可以根据项目的需求修改UIAlertView的颜色。有需要的朋友们可以参考借鉴,也可以多多指导,下面来一起看看吧。

ios-自定义AlertView,可图片可文字.zip

可以网络加载图片可网络加载文字,可自定义alertView颜色等等,东西很简单,但是我对颜色不敏感,所有设置的颜色不那么亮眼,代码很容易看懂,自己修改也方便。里面包含了mas框架。。

关于自定义UIAlertView背景的方法收集

从网上收集了一些自定义AlertView背景的方法,汇总一下以便有需要时使用。 UIAlertView *theAlert = [[[UIAlertView alloc] initWithTitle:@"Atention" message:@"我是中国人!" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil] au

ldz15838245189的专栏 778

自定义alertView

自定义alertView,继承自UIView,可以在消息区域添加子视图:addCustomerSubview 标题可以有图片+文字构成, 只支持两个按钮操作 // - 在需要alert的控制器调用 alertView show 方法 [objc] view plaincopy CustomAlertView *alertView = [[CustomAlertV

lzylzy1991的专栏 365

ios7 自定义alertview

升级到ios7后,旧项目中使用的继承UIAlertView自定义alertview无法正常显示了,无奈只好换思路去实现,改成从当前keywindow下创建要显示的alertview,并模仿了系统alertview   .h文件   #import typedef enum { CustomAlertViewType_Msg_TwoBtn=1,//含有title,提示

sadlike的专栏 1153

iOS UIAlertView和UIActionSheet的用法

这篇文章主要学习alertview 和 actionsheet这两个控件的使用。Action Sheet是从底部弹出,上面有2个或者2个以上的选项供用户选择,Alert就是一个警告框,上面有1个或者1个以上的按钮供用户进行选择。 (说明:其实这两个不是控件,而是ios 中的两个类,这里暂且这么叫吧。这2个类定义了2种不同类型的用于和用户交互的弹出框) 首先,使用这两个类要使用到其代理,UIAl

小邓笔记 3482
下一篇: iOS捕捉截屏事件并展示截图
SL_ideas
博客等级 码龄9年 16粉丝 8原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值