iOS自定义ActionSheet(轻模仿微信)

城市有我奋斗的青春.jpg

这波不多说废话直接来干的:

最近心情比较差还好工作不太忙,微博微信刷多了,感觉他们的Alert很漂亮模仿一下

ActionSheet使用说明:

初始化方法:

  • 初始化方法创建,之后调用响应的弹出和移除方法
  • 单例创建方式,调用创建Alert再调用弹出和移除就可以

点击事件处理

  • 使用代理带出相关index下标,title内容以及视图本身self(需要遵循代理实现代理方法)
  • 使用Block代码块传出响应的数据,以供使用(需要调用didSelectAlertBlock:方法)

自定义部分

  • ActionSheet的每个item的字体颜色,字号,行高可以自定义(比如alert.titleTextColor=[UIColor redColr])

效果图:

带内容提示.png
不带内容提示.png
楼底有demo地址

下面直接贴代码:

.h文件:
#import <UIKit/UIKit.h>
@class Dz_mostBeautifulAlert;

//******************************************************************
typedef NS_ENUM(NSUInteger, AlertStyle)
{   // 暂时没有投入使用
    AlertPositionInTop = 0,
    AlertPositionInBottom
};

//******************************************************************

typedef void(^DzAlertSelectBlock)(NSInteger index,NSString * title,Dz_mostBeautifulAlert * sender);

//******************************************************************

@protocol Dz_mostBeautifulAlertDelegate <NSObject>
// 代理方法,可以根据参数判断点击哪个
- (void)sheetViewDidSelectIndex:(NSInteger)index
                          title:(NSString *)title
                         sender:(id)sender;
// 点击取消按钮
- (void)cancelClickAction;
@end
@interface Dz_mostBeautifulAlert : UIView
// block
@property(copy,nonatomic)DzAlertSelectBlock block;
-(void)didSelectAlertBlock:(DzAlertSelectBlock)block;

// 代理
@property(weak,nonatomic)id<Dz_mostBeautifulAlertDelegate>delegate;

//******************************************************************
// 取消按钮字符串/默认取消
@property(strong,nonatomic)NSString* cancelItemStr;

//******************************************************************
// title字号/默认16
@property(strong,nonatomic)UIFont  * titleTextFont;

// item文字字号/默认16
@property(strong,nonatomic)UIFont  * itemTextFont;

// 取消按钮字号大小/默认16
@property(strong,nonatomic)UIFont  * cancelFont;

//******************************************************************
// title颜色 /默认黑色
@property(strong,nonatomic)UIColor * titleTextColor;

// 取消按钮字符颜色/默认红色
@property(strong,nonatomic)UIColor * cancelItemColor;

// item文字颜色/默认黑色
@property(strong,nonatomic)UIColor * itemTextColor;

// 分割线颜色/默认浅灰0.2透明度
@property(strong,nonatomic)UIColor * lineColor;

@property(assign,nonatomic)CGFloat itemHeight;

//******************************************************************
// 初始化方法
-(instancetype)initWithTitle:(NSString *)title style:(AlertStyle)style itemTitles:(NSArray *)items;//style暂时没有传nil就行

// 单例
+(id)sharedDzCustomAlert;
-(void)ceartAlertWithTitle:(NSString * )title style:(AlertStyle)style itemTitles:(NSArray*)items;
#pragma mark ---- 弹出和移除
//******************************************************************
// 调用此方法消失alert
-(void)dismissSheetView;
// 调用此方法推出alert
-(void)showAlert;
@end
.m文件:
#import "Dz_mostBeautifulAlert.h"
#define kW [UIScreen mainScreen].bounds.size.width
#define kH [UIScreen mainScreen].bounds.size.height
#define CH 40
#define HeaderH 15
#define FooterH 10

@interface Dz_mostBeautifulAlert ()<UITableViewDelegate,UITableViewDataSource>
{
    CGFloat tH; //tableView高度
}
@property(strong,nonatomic) UIView      * view;
@property(strong,nonatomic) UIView      * contentView;
@property(strong,nonatomic) UITableView * tableView;
// alert类型
@property(assign,nonatomic)AlertStyle alertStyle;
// 内容数组
@property(strong,nonatomic) NSArray * items;
// 提示语
@property(strong,nonatomic) NSString * title;


@end

static NSString * const tableViewCellIdenter = @"tableViewCellIdenter";
@implementation Dz_mostBeautifulAlert

+(id)sharedDzCustomAlert
{
    static Dz_mostBeautifulAlert * dzCustomAlert = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        dzCustomAlert = [[self.class alloc]init];
    });
    return dzCustomAlert;
}
-(void)ceartAlertWithTitle:(NSString *)title style:(AlertStyle)style itemTitles:(NSArray *)items
{
        self.backgroundColor = [UIColor lightGrayColor];
        _title = title;
        _items = items;
        _alertStyle = style;
}

-(instancetype)initWithTitle:(NSString *)title style:(AlertStyle)style itemTitles:(NSArray *)items
{
    if (self = [super init]) {
        self.backgroundColor = [UIColor lightGrayColor];
        _title = title;
        _items = items;
        _alertStyle = style;
    }
    return self;
}

#pragma mark -- tableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:{
            if (self.title.length == 0) {
                return _items.count;
            }else return _items.count+1;
        }
            break;
        case 1:{
            return 1;
        }
            break;
        default:{
            return 0;
        }
            break;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:tableViewCellIdenter forIndexPath:indexPath];
    [cell addSubview:[self topLineView:CGRectMake(0, cell.frame.size.height-1, kW,1)]];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.numberOfLines = 0;
    cell.backgroundView = [self returnTheToolbar];
    UIView * selectView =[UIView new];
    selectView.backgroundColor=[[UIColor lightGrayColor]colorWithAlphaComponent:0.1];
    cell.selectedBackgroundView =selectView;
    switch (indexPath.section) {
        case 0:{
            if (_title.length != 0) {
                if (indexPath.row ==0) {
                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                    cell.textLabel.text = self.title;
                    if (self.textColor) {
                        cell.textLabel.textColor = self.textColor;
                    }
                    if (self.titleTextFont) {
                        cell.textLabel.font = self.titleTextFont;
                    }
                }else{
                    cell.textLabel.text = self.items[indexPath.row-1];
                    if (self.itemTextFont) {
                        cell.textLabel.font = self.itemTextFont;
                    }
                    if (self.itemTextColor) {
                        cell.textLabel.textColor = self.itemTextColor;
                    }
                }
            }else{
                cell.textLabel.text = self.items[indexPath.row];
                if (self.itemTextFont){
                    cell.textLabel.font = self.itemTextFont;
                }
                if (self.itemTextColor){
                    cell.textLabel.textColor = self.itemTextColor;
                }
            }
        }
            break;
        case 1:{
            cell.textLabel.text = self.cancelItemStr;
            if (self.cancelFont) {
                cell.textLabel.font = self.cancelFont;
            }else cell.textLabel.font = [UIFont systemFontOfSize:16];
            if (self.cancelItemColor) {
                cell.textLabel.textColor =self.cancelItemColor;
            }else cell.textLabel.textColor = [UIColor redColor];
        }
            break;
        default:
            break;
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_title != nil) {// 有提示语
        if (indexPath.section==0&&indexPath.row==0) {
            if ([self cellHeightWithModel:self.title] > CH) {
                return [self cellHeightWithModel:self.title]+CH;
            }else return CH+15;
        }else{
            if (_itemHeight != 0) {
                return _itemHeight;
            }else return CH;
        }
    }else{
        if (_itemHeight != 0) {
            return _itemHeight;
        }else return CH;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return HeaderH;
    }else return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==1) {
        return FooterH;
    }else return 0;
}
// block处理点击事件
-(void)didSelectAlertBlock:(DzAlertSelectBlock)block
{
    _block=block;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"12312312313123");
//    if (_delegate &&[_delegate respondsToSelector:@selector(sheetViewDidSelectIndex:title:sender:)]){
//        [_delegate sheetViewDidSelectIndex:indexPath.row title:_items[indexPath.row] sender:self];
//    }
    
    if (_title.length != 0) {
        if (indexPath.section==0&&indexPath.row!=0) {
            if (_block) {
             self.block(indexPath.row-1,_items[indexPath.row-1],self);
            }
            if (_delegate &&[_delegate respondsToSelector:@selector(sheetViewDidSelectIndex:title:sender:)]){
                [_delegate sheetViewDidSelectIndex:indexPath.row-1 title:_items[indexPath.row-1] sender:self];
            }
        }
        if (indexPath.section == 1) {
            if (_block) {
                self.block(indexPath.row,self.cancelItemStr,self);
            }
            if (_delegate &&[_delegate respondsToSelector:@selector(cancelClickAction)]){
                if (self.cancelItemStr.length!=0) {
                    [_delegate cancelClickAction];
                }
            }
        }
    }else
    {
        if (indexPath.section==0) {
            if (_block) {
                self.block(indexPath.row,_items[indexPath.row],self);
            }
            if (_delegate &&[_delegate respondsToSelector:@selector(sheetViewDidSelectIndex:title:sender:)]){
                [_delegate sheetViewDidSelectIndex:indexPath.row title:_items[indexPath.row] sender:self];
            }
        }
        if (indexPath.section==1) {
            
            if (_block) {
                self.block(indexPath.row,_cancelItemStr,self);   
            }
            if (_delegate &&[_delegate respondsToSelector:@selector(cancelClickAction)]){
                if (self.cancelItemStr.length!=0) {
                    [_delegate cancelClickAction];
                }
            }
        }
    }
}
#pragma mark -- 交互
-(void)showAlert
{
    [[[UIApplication sharedApplication].delegate window].rootViewController.view addSubview:self];
    self.view = [[UIApplication sharedApplication].delegate window].rootViewController.view;
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.tableView];
    [self pushSheetView];
}
// 弹出
-(void)pushSheetView
{
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.contentView.frame = CGRectMake(0, kH - tH, kW, tH);
    }];
}
// 移除
-(void)dismissSheetView
{
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.contentView.frame = CGRectMake(0, kH-FooterH, kW, tH);
    } completion:^(BOOL finished) {
        [weakSelf.contentView removeFromSuperview];
    }];
}
// 线条View
-(UIView *)topLineView:(CGRect)frame
{
    UIView * view = [[UIView alloc]init];
    if (_lineColor) {
        view.backgroundColor = _lineColor;
    }else view.backgroundColor = [[UIColor lightGrayColor]colorWithAlphaComponent:0.2];
    view.frame = frame;
    return view;
}
// 计算高度
-(CGFloat)cellHeightWithModel:(NSString *)title
{
    // 不固定高度
    CGFloat dynamicHeight = [self getLabelHeightByWidth:kW - 60 Title:title font:[UIFont systemFontOfSize:13]];
    if (_itemHeight != 0) {
        if (dynamicHeight > _itemHeight) {
            return dynamicHeight+15;
        }else return _itemHeight;
    }else{
        if (dynamicHeight > CH) {
            return dynamicHeight+15;
        }else return CH;
    }
}
-(CGFloat)getLabelHeightByWidth:(CGFloat)width Title:(NSString *)title font:(UIFont *)font {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.text = title;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.frame.size.height;
    return height;
}

#pragma mark -- setter getter
-(NSArray *)items{
    if (!_items) {
        _items = [NSArray array];
    }
    return _items;
}
-(UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc]initWithFrame:CGRectMake(0,kH, kW, tH)];
    }
    return _contentView;
}
-(UIView *)returnTheToolbar
{
    UIView * view = [UIView new];
    UIToolbar * toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0,kH, kW, tH)];
    toolbar.alpha = 0.8;
    toolbar.backgroundColor = [UIColor whiteColor];
    [view addSubview:toolbar];
    return view;
}
-(UITableView *)tableView{
    if (!_tableView) {
        NSLog(@"item的高度是什么:%f",_itemHeight);
        if (_title.length==0){
            if (_itemHeight != 0) {
             tH=_items.count * _itemHeight + _itemHeight+HeaderH+FooterH;
            }else tH= _items.count*CH+CH+HeaderH+FooterH;
        }else
        {
            if (_itemHeight!=0) {
              tH=(_items.count+1)*_itemHeight+ _itemHeight+HeaderH+FooterH+15;//分区1高度+分区2高度+区头+区尾+第一行cell加的15
            }else tH=(_items.count+1)*CH+ CH+HeaderH+FooterH+15;//分区1高度+分区2高度+区头+区尾+第一行cell加的15
        }
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,kW,tH) style:(UITableViewStylePlain)];
        [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
        _tableView.backgroundView = [self returnTheToolbar];
        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:tableViewCellIdenter];
    }
    return _tableView;
}
-(NSString *)cancelItemStr
{
    if (!_cancelItemStr) {
        _cancelItemStr = @"取消";
    }
    return _cancelItemStr;
}
-(UIColor *)lineColor{
    if (!_lineColor) {
        _lineColor = [[UIColor lightGrayColor]colorWithAlphaComponent:0.1];
    }
    return _lineColor;
}
-(UIColor *)itemTextColor{
    if (!_itemTextColor) {
        _itemTextColor = [UIColor blackColor];
    }
    return _itemTextColor;
}
-(UIColor *)cancelItemColor{
    if (!_cancelItemColor) {
        _cancelItemColor = [UIColor redColor];
    }
    return _cancelItemColor;
}
-(UIColor *)textColor{
    if (!_titleTextColor) {
        _titleTextColor = [UIColor lightGrayColor];
    }
    return _titleTextColor;
}
-(UIFont *)textFont{
    if (!_titleTextFont) {
        _titleTextFont = [UIFont systemFontOfSize:16];
    }
    return _titleTextFont;
}
-(UIFont *)itemTextFont{
    if (!_itemTextFont) {
        _itemTextFont = [UIFont systemFontOfSize:16];
    }
    return _itemTextFont;
}
-(UIFont *)cancelFont
{
    if (!_cancelFont){
        _cancelFont = [UIFont systemFontOfSize:16];
    }
    return _cancelFont;
}

demo下载地址:

https://pan.baidu.com/s/1kVBczQZ

结束
(写这个Alert很大成分是为了发泄,心情不好就不说话戴耳机,使劲敲键盘,使劲发泄)
这次写简书的战歌: 血腥爱情故事+魔鬼中的天使
其实你是一个有梦想的孩子
不用怕现在的百无聊赖。时间到了,所有的好都会前赴后继的向你扑来,就怕你现在的努力太少驾驭不了,只能辜负。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,614评论 4 59
  • 昨天晚上从八点开始和小伙伴们打扑克,打到12点,室友还以为我俩发生了什么,打了好几个电话,这个东西还是真上瘾,这还...
    花儿的博文阅读 483评论 0 1
  • 喜欢周国平的思想文字,他的哲学观有很多让我产生共鸣,也有很多让我开始思考。既简单纯粹,又有深度。 读完周国平的《人...
    一只早鸟阅读 4,424评论 0 5