UIKit之UITableView

UITableView基礎(chǔ)使用

View.m中

  // 都是一樣的cell, 只有一個(gè)分組
    self.tableView = [[UITableView alloc]initWithFrame:self.frame style:UITableViewStylePlain];
    // 帶分組的tableView
    self.tableView = [[UITableView alloc]initWithFrame:self.frame style:UITableViewStyleGrouped];
    // 1. 設(shè)置行高
    self.tableView.rowHeight = 100;
   
    // 2. 設(shè)置分割線的顏色和樣式
    self.tableView.separatorColor = [UIColor magentaColor];
    // tableView 上面展示的每一條數(shù)據(jù)都是放在 一個(gè)cell上面
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

Controller.m中

// 以后養(yǎng)成習(xí)慣(直接把兩個(gè)方法直接都寫上)
@interface RootViewController ()<UITableViewDataSource,UITableViewDelegate>

// 直接設(shè)置兩個(gè)代理
self.rootV.tableView.dataSource = self;
self.rootV.tableView.delegate = self;

//  設(shè)置tableView (Section)分組數(shù)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
// 設(shè)置tableView (row)每個(gè)分組的行數(shù)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    int a = 0;
    switch (section) {
        case 0:
            a = 1;
            break;
        case 1:
            a = 3;
            break;
        case 2:
            a = 1;
            break;
        case 3:
            a = 1;
            break;
        default:
            break;
    }
    return a;
}

3. 設(shè)置每條cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // cell的reuseldentifier是重用機(jī)制的關(guān)鍵
    // 1. 聲明一個(gè)重用標(biāo)識(shí)符(唯一)
    static NSString *cell_id = @"cell";
    // 2. 去重用池尋找有次標(biāo)識(shí)符的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    // 3. 判斷
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_id];
    }
    // 注意:重用池是由一個(gè)NSMutableSet實(shí)現(xiàn)的 iOS為了保證內(nèi)存的合理使用,提供了重用機(jī)制,劃出屏幕的 cell 被放到重用池中,加上了一個(gè)重用標(biāo)識(shí)符,如果下次使用,直接使用帶標(biāo)識(shí)符的cell即可
    cell.textLabel.text = @"張三";
    cell.detailTextLabel.text = @"張三簡(jiǎn)介";
    return cell;
}


// 設(shè)置分區(qū)頭部的標(biāo)題
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [NSString stringWithFormat:@"聯(lián)系人"];
}
// 設(shè)置尾部標(biāo)題
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    return @"結(jié)束";
}
// 顯示右側(cè)豎排索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSArray *arr = @[@"0",@"1",@"2",@"3"];
    return arr;
}

#pragma mark UITableViewDelegate
// 返回header 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
// 返回hearder的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *temp = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    //temp.backgroundColor = [UIColor grayColor];
    return temp;
}
// 返回footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 50;
}
// 返回footer的view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *temp = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    temp.backgroundColor = [UIColor blackColor];
    return temp;
}
// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2 && indexPath.row == 2) {
        return 30;
    }else
    return 100;
}

// 選中某一行(千萬(wàn)別寫錯(cuò)方法)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.row == 1 && indexPath.section == 2) {
//        NSLog(@"aaaaaaaa");
//    }
    NextViewController *nextVC = [[NextViewController alloc]init];
    //[self.navigationController pushViewController:nextVC animated:YES];

// 模態(tài)實(shí)現(xiàn)
  [self.navigationController presentViewController:nextVC animated:YES completion:^{
  }];
}

Cell增刪 移動(dòng)


#import"RootViewController.h"
#import "RootView.h"

@interface RootViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,retain)RootView *rootV;
@property(nonatomic,retain)NSMutableArray *allArr;
@property(nonatomic,assign)UITableViewCellEditingStyle editStyle;

@end

@implementation RootViewController
- (void)loadView{
    self.rootV = [[RootView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = self.rootV;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self p_date];
   
    self.rootV.tableView.delegate = self;
    self.rootV.tableView.dataSource = self;
   
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"刪除" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];

}
設(shè)置分組數(shù) (section)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.allArr.count;
}
設(shè)置每個(gè)分組的行數(shù) (row)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.allArr[section] count];
}
設(shè)值每個(gè)Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cell_id = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_id];
    }
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    cell.textLabel.text = self.allArr[indexPath.section][indexPath.row];
    return cell;
}
 數(shù)據(jù)處理
- (void)p_date{
    self.allArr = [NSMutableArray array];
    NSMutableArray * arr1 = @[@"孫行者",@"者行孫",@"行者孫"].mutableCopy;
    NSMutableArray *arr2 = @[@"大師兄,師傅被妖怪抓走了",@"大師兄,二師兄被妖怪抓走了",@"大師兄,白龍馬被妖怪抓走了",@"大師兄,我被妖怪抓走了"].mutableCopy;
    [self.allArr addObject:arr1];
    [self.allArr addObject:arr2];
}
增刪
// 1. 處于編輯狀態(tài)
- (void)rightAction:(UIBarButtonItem *)sender{
    _editStyle = UITableViewCellEditingStyleDelete;
    [self.rootV.tableView setEditing:!self.rootV.tableView.editing animated:YES];
}
- (void)leftAction:(UIBarButtonItem *)sender{
    _editStyle = UITableViewCellEditingStyleInsert;
    [self.rootV.tableView setEditing:!self.rootV.tableView.editing animated:YES];
}
//2. 指定哪一行可以被編輯
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
// 3. 設(shè)置編輯樣式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{

    return self.editStyle;
}
// 4. 完成編輯(1. 修改數(shù)據(jù)源 2. 修改UI)
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.editStyle == UITableViewCellEditingStyleInsert) {
        // 1.修改數(shù)據(jù)源
        [self.allArr[indexPath.section] insertObject:@"aaa" atIndex:indexPath.row + 1];
        // 2. 修改UI
        NSIndexPath *temp = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        [self.rootV.tableView insertRowsAtIndexPaths:@[temp] withRowAnimation:UITableViewRowAnimationLeft];
    }else{
        [self.allArr[indexPath.section] removeObjectAtIndex:indexPath.row];
        [self.rootV.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}

移動(dòng)
// 1. 設(shè)置處于編輯狀態(tài)
// 2. 指定哪一行可以被移動(dòng)
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
// 3. 完成移動(dòng)
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
   
    if (sourceIndexPath.section == destinationIndexPath.section) {
        [self.allArr[sourceIndexPath.section] exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
    }else{
        [self.allArr[destinationIndexPath.section] insertObject:self.allArr[sourceIndexPath.section][sourceIndexPath.row] atIndex:destinationIndexPath.row];
        [self.allArr[sourceIndexPath.section] removeObjectAtIndex:sourceIndexPath.row];
    }
//    // 1. 拿出數(shù)據(jù)
//    NSString *temp = self.allArr[sourceIndexPath.section][sourceIndexPath.row];
//    // 從數(shù)組中刪除
//    [self.allArr[sourceIndexPath.section] removeObjectAtIndex:sourceIndexPath.row];
//    // 插入到新的位置
//    [self.allArr[destinationIndexPath.section] insertObject:temp atIndex:destinationIndexPath.row];
   
    // iOS tableViewCell 不建議跨區(qū)移動(dòng),,必須想辦法限制
}
//  設(shè)置禁止跨分組移動(dòng)
//- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
//{
//    if (sourceIndexPath.section == proposedDestinationIndexPath.section) {
//        return proposedDestinationIndexPath;
//    }else{
//        return sourceIndexPath;
//    }
//}

UITableViewController注意事項(xiàng)

// 1. 先注冊(cè)
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
// 2. 修改identifier(標(biāo)識(shí)符) 為@"cell"
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

自定義Cell和Model

1. plist文件
   NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Property List" ofType:@"plist"];
   NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
2.Cell_Model
// 1. 新建類 繼承于 NSObject 專門處理數(shù)據(jù)
@interface Person : NSObject
// .h寫屬性 是跟后臺(tái)的數(shù)據(jù)對(duì)應(yīng)的(名字必須對(duì)應(yīng))
@property(nonatomic,retain)NSString *ImageName;
@property(nonatomic,retain)NSString *personName;
@end

#import "Person.h"
@implementation Person
// 2. 為了防止后臺(tái)數(shù)據(jù)里的key 跟屬性名不一樣  必須在.m里面洗這個(gè)方法,防止程序崩潰
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
@end
自定義cell 和model的使用
#import <UIKit/UIKit.h>
@class Person;
@interface MyCell : UITableViewCell
@property(nonatomic,retain)UIImageView *myImage;
@property(nonatomic,retain)UILabel *nameLabel;
// 3 . 寫方法把獲取的數(shù)據(jù)傳給cell
- (void)personValue:(Person *)aPerson;
@end

//************************************自定義Cell************************************
#import "MyCell.h"
#import "Person.h"
@implementation MyCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self p_setupView];
    }
    return self;
}
- (void)p_setupView{
    self.myImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 60, 60)];
    self.myImage.backgroundColor = [UIColor blueColor];
    [self.contentView addSubview:self.myImage];

    self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.myImage.frame) + 10, CGRectGetMinY(self.myImage.frame),CGRectGetWidth(self.contentView.frame) - CGRectGetWidth(self.myImage.frame) - 30, CGRectGetHeight(self.myImage.frame))];
    self.nameLabel.backgroundColor = [UIColor yellowColor];
    [self.contentView addSubview:self.nameLabel ];
}
// 當(dāng)bounds改變的時(shí)候結(jié)構(gòu)也跟著改變
- (void)layoutSubviews{
    self.nameLabel.frame = CGRectMake(CGRectGetMaxX(self.myImage.frame) + 10,
                                      CGRectGetMinY(self.myImage.frame),
                                      CGRectGetWidth(self.contentView.frame) - CGRectGetWidth(self.myImage.frame) - 30,
                                      CGRectGetHeight(self.myImage.frame));
}
// 傳數(shù)據(jù)給cell
// 4 .(實(shí)現(xiàn))利用傳進(jìn)來(lái)的model類,給cell空間的屬性進(jìn)行賦值
- (void)personValue:(Person *)aPerson{
    self.myImage.image = [UIImage imageNamed:aPerson.ImageName];
    self.nameLabel.text = aPerson.personName;
}
//************************************自定義Cell************************************

#import "RootTableViewController.h"
#import "MyCell.h"
#import "Person.h"
@interface RootTableViewController ()
// 5. 創(chuàng)建一個(gè)字典 用來(lái)存儲(chǔ)dict信息
@property(nonatomic,retain)NSMutableDictionary *personDict;
@property(nonatomic,retain)NSMutableArray *GroupName;
@end
@implementation RootTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
// 1. 注冊(cè)
    [self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"cell"]
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self p_date];
}
- (void)p_date{
    // 6. 拿到后臺(tái)數(shù)據(jù)
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Property List" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    self.GroupName = [NSMutableArray array];
    self.personDict = [NSMutableDictionary dictionary];
    // 遍歷dict字典 獲得key
    for (NSString *key in dict) {
        NSMutableArray *temp = [NSMutableArray array];
        // 把遍歷出來(lái)的key 存到 字典中
        [self.personDict setObject:temp forKey:key];
        // 把key存到一個(gè)數(shù)組中
        [self.GroupName addObject:key];
        //遍歷字典存儲(chǔ)的數(shù)組 獲取數(shù)組中每個(gè)存儲(chǔ)個(gè)人信息的字典
        for (NSDictionary *d in dict[key]) {
            Person *p = [[Person alloc]init];
            // KVC
            // 將存儲(chǔ)每個(gè)人的字典的鍵值對(duì), 賦值給person
            [p setValuesForKeysWithDictionary:d];
            // 將person 存儲(chǔ)到字典中
            [self.personDict[key] addObject:p];
        }
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // 7.返回 字典里面的分組數(shù)
    return self.GroupName.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 8. 返回字典中每個(gè)分組中person的個(gè)數(shù)
    NSArray *temp = [self.personDict objectForKey:self.GroupName[section]];
    return temp.count;
    //return  [[self.personDict objectForKey:self.GroupName[section]] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSArray *tempArr = [self.personDict objectForKey:self.GroupName[indexPath.section]];
    Person *tempPerson = tempArr[indexPath.row];
    [cell personValue:tempPerson];
    return cell;
}
// 設(shè)置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

多種Cell混合使用、懶加載

1. 多種Cell的混合使用
// 創(chuàng)建不同的Cell 根據(jù)if條件判斷使用哪個(gè)Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    Person *p = self.dateArr[indexPath.row];
    if ([p.gender isEqualToString:@"男"]) {
        BoyCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell1.boyLabel.text = p.name;
        return cell1;
    }else{
        GirlCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell2.girlImage.image =[ UIImage imageNamed:p.name];
        return cell2;
    }
}
2. 自定義Cell高度 (懶加載)
// 懶加載 (延遲加載)  有了它以前的自定義初始化就不用寫,剛剛相當(dāng)于重寫了屬性的getter方法  方法里面只需要做  是否為空的判斷即可
- (UILabel *)myLabel{
    if (_myLabel == nil) {
        self.myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, CGRectGetWidth(self.contentView.frame) - 20, 60)];
        self.myLabel.backgroundColor = [UIColor grayColor];
        [self.contentView addSubview:self.myLabel];
    }
    return _myLabel;// 寫 return 和 if 條件 的時(shí)候?qū)?_的實(shí)例變量
}

#import "RootTableViewController.h"
#import "MyTableViewCell.h"

@interface RootTableViewController ()

@property(nonatomic,retain)NSString *contentStr;
@end

@implementation RootTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self.tableView registerClass:[MyTableViewCell class] forCellReuseIdentifier:@"cell"];
   // self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.contentStr = [NSString stringWithFormat:@"從南邊來(lái)了個(gè)喇嘛,提拉著五斤塔嘛。從北邊來(lái)個(gè)啞吧,腰里別著個(gè)喇叭,提拉塔嘛的喇嘛,要拿塔嘛換別喇叭啞巴的喇叭,別喇叭的啞巴,不愿意拿喇叭換提拉塔嘛喇嘛的塔嘛。提拉塔嘛的喇嘛拿塔嘛打了別喇叭的啞巴一塔嘛,別喇叭的啞巴,拿喇叭打了提拉塔嘛的喇嘛一喇叭。也不知提拉塔嘛的喇嘛拿塔嘛打壞了別喇叭啞巴的喇叭。也不知?jiǎng)e喇叭的啞巴拿喇巴打壞了提拉塔嘛喇嘛的塔嘛。提拉塔嘛的喇嘛敦塔嘛,別喇叭的啞巴吹喇叭"];
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
   
    // Configure the cell...
    CGRect  tempRect = cell.myLabel.frame;
    CGFloat tempFloat = [self stringHeight:self.contentStr];
    tempRect.size.height = tempFloat;
    cell.myLabel.frame = tempRect;
   
    cell.myLabel.text = self.contentStr;
    cell.myLabel.numberOfLines = 0;
   
    cell.myLabel.font = [UIFont systemFontOfSize:16];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self stringHeight:self.contentStr] + 20;
}
- (CGFloat)stringHeight:(NSString *)aString{
    CGRect rect = [aString boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width - 20, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16.5]} context:nil];
    // 選擇size一定要大于等于實(shí)際的字體
    return rect.size.height;
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 掌握 設(shè)置UITableView的dataSource、delegate UITableView多組數(shù)據(jù)和單組數(shù)據(jù)...
    JonesCxy閱讀 1,402評(píng)論 0 2
  • UITableViewCell控件空間構(gòu)造 cell的子控件是contentView,contentView的子控...
    CoderZXS閱讀 852評(píng)論 0 1
  • 前言 最近忙完項(xiàng)目比較閑,想寫一篇博客來(lái)分享一些自學(xué)iOS的心得體會(huì),希望對(duì)迷茫的你有所幫助。博主非科班出身,一些...
    GitHubPorter閱讀 1,588評(píng)論 9 5
  • 1.UITableViewCell高度計(jì)算 Cell 具有固定高度的情況,使用rowHeight;之類的設(shè)置高度 ...
    陳勝華閱讀 351評(píng)論 0 0
  • 概述在iOS開發(fā)中UITableView可以說(shuō)是使用最廣泛的控件,我們平時(shí)使用的軟件中到處都可以看到它的影子,類似...
    liudhkk閱讀 9,300評(píng)論 3 38

友情鏈接更多精彩內(nèi)容