iOS UITableView配合block 回調(diào)實(shí)現(xiàn)列表刪除教程

前言:

各位同學(xué)大家好 裳食,有段時(shí)間沒(méi)有給大家更新文章了 幕与。 具體多久我也記不清楚了疗琉,春節(jié)放假比較早雁竞,所以就趁著有時(shí)間學(xué)習(xí)了一下iOS開(kāi)發(fā)的基礎(chǔ)知識(shí) 今天講的iOS UITableView 配和block 回調(diào)實(shí)現(xiàn)列表刪除教程 簿寂。那么廢話不多說(shuō) 漾抬,我們正式開(kāi)始。

準(zhǔn)備工作

安裝xcode 這個(gè)大家可以自己去appstore 搜索下載安裝即可

效果圖

QQ20210210-160354-HD[00_00_00--00_00_08].gif

具體實(shí)現(xiàn)

  • 列表顯示
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,GTNotmalTableViewDelegate>
@property(nonatomic,strong,readwrite)UITableView * tableview;
@property(nonatomic,strong,readwrite)NSMutableArray * dataArray;
@end
@implementation ViewController
- (instancetype)init{
    self= [super init];
    if(self){
        _dataArray=@[].mutableCopy;
        for(int i=0; i<20;i++){
            [_dataArray addObject:@(i)];
        } 
    }
    return  self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor= [UIColor whiteColor];
    _tableview= [[UITableView alloc]initWithFrame:self.view.bounds];
    _tableview.dataSource=self;
    _tableview.delegate=self;
    [self.view addSubview:_tableview];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110 ;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld", indexPath.row)
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
  //UItableview cell 復(fù)用機(jī)制
    GTNormalTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"id"];
    if(!cell){
    cell =[[GTNormalTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
                                reuseIdentifier:@"id"];
        cell.deledate=self;
    }
    [cell layoutTableViewCell];
    return  cell;
}
- (void) tableviewCell:(UITableViewCell *)tabviewCell clickDeleteButton:(UIButton * )deletebutton{
    NSLog(@"clickDeleteButton");
    GTDeleteCellView * deleteview =[[GTDeleteCellView alloc] initWithFrame:self.view.bounds];
    CGRect  rect =[tabviewCell  convertRect:deletebutton.frame  toView:nil];
    __weak typeof(self)wself= self;
    [deleteview showDeleteViewFromPoint:rect.origin clickBlock:^{
        __strong typeof  (self)strongSelf=wself;
        [strongSelf.dataArray removeLastObject];
        NSLog(@"clickBlock  回調(diào)");
        [self.tableview deleteRowsAtIndexPaths:@[[strongSelf.tableview indexPathForCell:tabviewCell]]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    
    } ];

}
@end

我們這邊調(diào)用系統(tǒng)的 UITableView 組件 實(shí)例化 然后添加自定義的cell 來(lái)實(shí)現(xiàn) 整個(gè)列表的展示

  • 添加自定義的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  //UItableview cell 復(fù)用機(jī)制
    GTNormalTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"id"];
    if(!cell){
    cell =[[GTNormalTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
                                reuseIdentifier:@"id"];
        cell.deledate=self;
    }
    [cell  layoutTableViewCell];
    return  cell;
}
  • 自定義 cell 內(nèi)容
//
//  GTNormalTableViewCell.m
//  shop
//
//  Created by xuqing on 2021/1/27.
//  Copyright ? 2021 xuqing. All rights reserved.
//
#import "GTNormalTableViewCell.h"
@interface GTNormalTableViewCell()
@property(nonatomic,strong,readwrite)UILabel * titleLable;
@property(nonatomic,strong,readwrite)UILabel * sourceLable;
@property(nonatomic,strong,readwrite)UILabel * commentLable;
@property(nonatomic,strong,readwrite)UILabel * timeLable;
@property(nonatomic,strong,readwrite)UIImageView *richtimageview;
@property(nonatomic,strong,readwrite)UIButton* deletebutton;
@end

@implementation GTNormalTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)
      reuseIdentifier {
    self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        [self.contentView addSubview:({
            self.titleLable=[[UILabel alloc]initWithFrame:CGRectMake(20, 15, 300, 50)];
           // self.titleLable.backgroundColor=[UIColor redColor];
            self.titleLable;
        })];
        [self.contentView addSubview:({
            self.sourceLable=[[UILabel alloc]initWithFrame:CGRectMake(20, 80, 50, 20)];
          //  self.sourceLable.backgroundColor=[UIColor redColor];
            self.sourceLable;


        })];
        [self.contentView addSubview:({
            self.commentLable=[[UILabel alloc]initWithFrame:CGRectMake(100 ,80, 50, 20)];
           // self.commentLable.backgroundColor=[UIColor redColor];
            self.commentLable;
        })];


        [self.contentView addSubview:({
            self.timeLable=[[UILabel alloc]initWithFrame:CGRectMake(150, 80, 50, 20)];
          //  self.timeLable.backgroundColor=[UIColor redColor];
            self.timeLable;
        })];
        
        
        [self.contentView addSubview:({
            self.richtimageview=[[UIImageView alloc]initWithFrame:CGRectMake(330, 15, 70, 70)];
            self.richtimageview.backgroundColor=[UIColor redColor];
            self.richtimageview;
        })];
        
        
        [self.contentView addSubview:({
            self.deletebutton=[[UIButton alloc]initWithFrame:CGRectMake(290, 80, 30,20)];
            self.deletebutton.backgroundColor=[UIColor blueColor];
            [self.deletebutton setTitle:@"X" forState:UIControlStateNormal];
            [self.deletebutton setTitle:@"V" forState:UIControlStateHighlighted];
            [self.deletebutton addTarget:self action:@selector(deletebuttonClick) forControlEvents:UIControlEventTouchUpInside];
            
            self.deletebutton;
        })];
    
    }
    return  self;
}


- (void)layoutTableViewCell{
    self.titleLable.text=@"極客時(shí)間iOS開(kāi)發(fā)";
    self.sourceLable.text=@"極客時(shí)間";
    [self.sourceLable sizeToFit];

    self.commentLable.text=@"1999評(píng)論";
    [self.commentLable sizeToFit];
    self.commentLable.frame= CGRectMake(self.sourceLable.frame.origin.x+self.commentLable.frame.size.width+15,
                                        self.commentLable.frame.origin.y,   self.commentLable.frame.size.width, self.commentLable.frame.size.height);
    self.timeLable.text=@"三分鐘前";
    [self.timeLable sizeToFit];
    self.timeLable.frame= CGRectMake(self.commentLable.frame.origin.x+self.commentLable.frame.size.width+15,
                                     self.timeLable.frame.origin.y,   self.timeLable.frame.size.width, self.timeLable.frame.size.height);
}
- (void)deletebuttonClick{
    NSLog(@"deletebuttonClick");
    if(self.deledate &&[self.deledate respondsToSelector:@selector(tableviewCell:clickDeleteButton:)]){
        [self.deledate tableviewCell:self clickDeleteButton:self.deletebutton];
    }
}
@end

為我們的刪除按鈕添加點(diǎn)擊onClick 事件

[self.deletebutton addTarget:self action:@selector(deletebuttonClick) forControlEvents:UIControlEventTouchUpInside];
  • 具體點(diǎn)擊事件
- (void)deletebuttonClick{
    NSLog(@"deletebuttonClick");
    if(self.deledate &&[self.deledate respondsToSelector:@selector(tableviewCell:clickDeleteButton:)]){
        [self.deledate tableviewCell:self clickDeleteButton:self.deletebutton];
    }
}

我們?cè)赾ell子布局里面的刪除按鈕的點(diǎn)擊事件調(diào)用了 clickDeleteButton 方法

@protocol GTNotmalTableViewDelegate <NSObject>
- (void) tableviewCell:(UITableViewCell *)tabviewCell clickDeleteButton:(UIButton * )deletebutton;
@end

然后 我們?cè)赩iewController 中實(shí)現(xiàn)clickDeleteButton 方法

- (void) tableviewCell:(UITableViewCell *)tabviewCell clickDeleteButton:(UIButton * )deletebutton{
    NSLog(@"clickDeleteButton");
    GTDeleteCellView * deleteview =[[GTDeleteCellView alloc] initWithFrame:self.view.bounds];
    CGRect  rect =[tabviewCell  convertRect:deletebutton.frame  toView:nil];
    __weak typeof(self)wself= self;
    [deleteview showDeleteViewFromPoint:rect.origin clickBlock:^{
        __strong typeof  (self)strongSelf=wself;
        [strongSelf.dataArray removeLastObject];
        NSLog(@"clickBlock  回調(diào)");
        [self.tableview deleteRowsAtIndexPaths:@[[strongSelf.tableview indexPathForCell:tabviewCell]]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    } ];
}

我們?cè)? clickDeleteButton 方法中初始化GTDeleteCellView 并顯示

  • 彈出 GTDeleteCellView 具體實(shí)現(xiàn)
- (instancetype) initWithFrame:(CGRect)frame{
    
    self= [super initWithFrame:frame];
    if(self){
        
       [self addSubview:({
           _backgroundView=[[UIView alloc]initWithFrame:self.bounds];
           _backgroundView.backgroundColor=[UIColor blackColor];
           _backgroundView.alpha=0.5;
           [_backgroundView addGestureRecognizer:({
               UITapGestureRecognizer * tapGesture= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissDeleteView)];
               tapGesture;
           })];
           _backgroundView;
       })];
        [self addSubview:({
            _deleteButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
            _deleteButton.titleLabel.textColor = [UIColor whiteColor];
            _deleteButton.titleLabel.text=@"刪除";
            [_deleteButton addTarget:self action:@selector(_clickButton) forControlEvents:UIControlEventTouchUpInside];
            _deleteButton.backgroundColor=[UIColor redColor];
           _deleteButton;
        })];
    }
    return  self;
}

GTDeleteCellView 的顯示和關(guān)閉

  • 顯示

-(void)showDeleteViewFromPoint:(CGPoint)point  clickBlock:(dispatch_block_t)clickBlock{
    _deleteButton.frame=CGRectMake(point.x, point.y, 0, 0);
    _deleteBlock=[clickBlock copy];
    UIWindow *window =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    [window addSubview:self];
  //  [[UIApplication sharedApplication].keyWindow addSubview:self];
//   [UIView animateWithDuration:1.f animations:^{
//       self.deleteButton.frame=CGRectMake((self.bounds.size.width-200)/2 , (self.bounds.size.height-200)/2, 200, 200);
//   }];
//
    [UIView animateWithDuration:1.f delay:0.f usingSpringWithDamping:0.5  initialSpringVelocity:0.5 options:UIViewAnimationCurveEaseInOut
                     animations:^{
     self.deleteButton.frame=CGRectMake((self.bounds.size.width-200)/2 , (self.bounds.size.height-200)/2, 200, 200);
 }completion:^(BOOL finished){
  
     NSLog(@"completion");
   
 }];
  
}

showDeleteViewFromPoint 方法需要外部傳入 CGPoint 和block 的回調(diào)實(shí)現(xiàn) 然后showDeleteViewFromPoint 方法里面我們處理 GTDeleteCellView 彈出的的動(dòng)畫(huà)效果

  • 動(dòng)畫(huà)
 [UIView animateWithDuration:1.f delay:0.f usingSpringWithDamping:0.5  initialSpringVelocity:0.5 options:UIViewAnimationCurveEaseInOut
                     animations:^{
     self.deleteButton.frame=CGRectMake((self.bounds.size.width-200)/2 , (self.bounds.size.height-200)/2, 200, 200);
 }completion:^(BOOL finished){
     NSLog(@"completion")常遂;
 }];

實(shí)例化block 和point

    _deleteButton.frame=CGRectMake(point.x, point.y, 0, 0);
    _deleteBlock=[clickBlock copy];
    UIWindow *window =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    [window addSubview:self];
  • 關(guān)閉

-(void)dismissDeleteView{
    [self removeFromSuperview];
}

這是點(diǎn)空白的地方關(guān)閉
我們給deletebutton 添加點(diǎn)擊事件

  [_deleteButton addTarget:self action:@selector(_clickButton) forControlEvents:UIControlEventTouchUpInside];

我們?cè)邳c(diǎn)擊事件方法實(shí)現(xiàn)里面 調(diào)用 block和 removeFromSuperview

-(void)_clickButton{
 //   _deleteBlock();
    if(_deleteBlock){
        _deleteBlock();
        NSLog(@"block回調(diào)執(zhí)行");
    }
    [self removeFromSuperview];
}

這樣我們的deletebutton點(diǎn)擊就也會(huì)關(guān)閉 GTDeleteCellView
然后我們?cè)? ViewController 中將block 的會(huì)回調(diào)實(shí)現(xiàn) 并且刪除dataArray數(shù)組里面的數(shù)據(jù)更新列表

CGRect  rect =[tabviewCell  convertRect:deletebutton.frame  toView:nil];
    __weak typeof(self)wself= self;
    [deleteview showDeleteViewFromPoint:rect.origin clickBlock:^{
        __strong typeof  (self)strongSelf=wself;
        [strongSelf.dataArray removeLastObject];
        NSLog(@"clickBlock  回調(diào)");
        [self.tableview deleteRowsAtIndexPaths:@[[strongSelf.tableview indexPathForCell:tabviewCell]]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    
    } ];

我們調(diào)用 GTDeleteCellView 中的showDeleteViewFromPoint 方法傳入我們轉(zhuǎn)換后的point 和block 的實(shí)現(xiàn)
最后我們調(diào)用

 [strongSelf.dataArray removeLastObject];

刪除數(shù)組里面的數(shù)據(jù) 然后調(diào)用 deleteRowsAtIndexPaths刪除并刷新列表

 [self.tableview deleteRowsAtIndexPaths:@[[strongSelf.tableview indexPathForCell:tabviewCell]]
                              withRowAnimation:UITableViewRowAnimationAutomatic];

到此iOS UITableView配合block 回調(diào)實(shí)現(xiàn)列表刪除教程就講完了

最后總結(jié)

在iOS開(kāi)發(fā)中這種列表展示基本都是使用 UITableView 和UICollectionView 我這邊只是加單舉例所以直接就用UITableView 實(shí)現(xiàn)了 我們要注意的是block回調(diào)使用和動(dòng)畫(huà)的處理 以及自定義cell的處理 就差不多了 纳令,我是一名安卓程序員 因?yàn)樾枰蛠?lái)學(xué)習(xí)一下iOS的開(kāi)發(fā), 最近看了一下教程學(xué)習(xí)了IOS里面的一些基礎(chǔ)控件的用法。 就想著做個(gè)筆記 所以就寫(xiě)了這篇文章 克胳,記錄一下 如果有錯(cuò)誤的請(qǐng)大神們指出平绩。 最后希望我的文章能幫助到各位解決問(wèn)題 ,以后我還會(huì)貢獻(xiàn)更多有用的代碼分享給大家漠另。各位同學(xué)如果覺(jué)得文章還不錯(cuò) 捏雌,麻煩給關(guān)注和star,小弟在這里謝過(guò)啦

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末笆搓,一起剝皮案震驚了整個(gè)濱河市性湿,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌满败,老刑警劉巖肤频,帶你破解...
    沈念sama閱讀 219,270評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異算墨,居然都是意外死亡宵荒,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)报咳,“玉大人侠讯,你說(shuō)我怎么就攤上這事∩傩ⅲ” “怎么了继低?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,630評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)稍走。 經(jīng)常有香客問(wèn)我,道長(zhǎng)柴底,這世上最難降的妖魔是什么婿脸? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,906評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮柄驻,結(jié)果婚禮上狐树,老公的妹妹穿的比我還像新娘。我一直安慰自己鸿脓,他們只是感情好抑钟,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著野哭,像睡著了一般在塔。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上拨黔,一...
    開(kāi)封第一講書(shū)人閱讀 51,718評(píng)論 1 305
  • 那天蛔溃,我揣著相機(jī)與錄音,去河邊找鬼篱蝇。 笑死贺待,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的零截。 我是一名探鬼主播麸塞,決...
    沈念sama閱讀 40,442評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼涧衙!你這毒婦竟也來(lái)了哪工?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,345評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤绍撞,失蹤者是張志新(化名)和其女友劉穎正勒,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體傻铣,經(jīng)...
    沈念sama閱讀 45,802評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡章贞,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鸭限。...
    茶點(diǎn)故事閱讀 40,117評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蜕径,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出败京,到底是詐尸還是另有隱情兜喻,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評(píng)論 5 346
  • 正文 年R本政府宣布赡麦,位于F島的核電站朴皆,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏泛粹。R本人自食惡果不足惜遂铡,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望晶姊。 院中可真熱鬧扒接,春花似錦、人聲如沸们衙。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,011評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蒙挑。三九已至宗侦,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間脆荷,已是汗流浹背凝垛。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,139評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蜓谋,地道東北人梦皮。 一個(gè)月前我還...
    沈念sama閱讀 48,377評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像桃焕,于是被迫代替她去往敵國(guó)和親剑肯。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評(píng)論 2 355

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