您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UITableView 靜態與動態單元格:從固定清單到可配置列表

編輯:iOS 開發綜合

一、靜態單元格:畫面寫死在 Storyboard 上

先看目標畫面:

這個介面整頁都是一個 tableview,內容固定、幾乎不會變動。要做出來有三條路:

  1. 用程式碼硬寫死組數、行數與內容——能跑,但這種「寫死」的程式碼不該出現。
  2. 把資料放進 plist 再用懶載入讀出來——較有彈性,但這裡的結構需要模型巢狀,反而更麻煩。
  3. 用 storyboard 的靜態單元格(Static Cells),所見即所得,最省事。(不過要說清楚:實際專案中很少這樣做。)

二、靜態單元格的設定流程

如果整頁就是一個列表,讓控制器直接繼承 UITableViewController 最合適。

把 storyboard 上預設的 view 刪掉,改拖一個 view controller 進來。

拖進來之後它預設帶一個 cell,而且是動態的(在畫面上看不到內容)。要改成靜態,得在屬性面板把 Content 設為 Static Cells——這一步沒改,後面全都白做。

接著把它和主控制器關聯起來。

之後就能逐一設定圖片與文字。標題有兩種改法:直接雙擊 cell,或點選內部的 label 修改。

輔助視圖(右側的箭頭、勾選、開關等)也在同一個面板設定。

組數透過 tableview 的 Sections 屬性決定:

每組的行數則直接複製貼上 cell 即可。

小技巧:若某幾列的樣貌完全相同,先做好一列再複製貼上、微調內容,比從頭拉快得多。但務必記得,靜態單元格在真實專案中只是知識點,正式開發走的還是動態路線。

三、動態單元格:實作可配置的 App 管理頁

目標畫面是一個 App 列表,每列有圖示、名稱、大小與下載量,右側一顆下載按鈕。

1. 專案結構與資料來源

2. 在 storyboard 中設定

把 tableview 的 Content 選為 Dynamic Prototypes,然後拉一個自訂 cell 類別並完成連線。

3. 模型層

// YYappInfo.h
@interface YYappInfo : NSObject
@property (nonatomic, copy) NSString *size;
@property (nonatomic, copy) NSString *download;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *name;

- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)appInfoWithDict:(NSDictionary *)dict;
@end
// YYappInfo.m
@implementation YYappInfo

- (instancetype)initWithDict:(NSDictionary *)dict {
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];   // 用 KVC 一次帶入全部同名字段
    }
    return self;
}

+ (instancetype)appInfoWithDict:(NSDictionary *)dict {
    return [[self alloc] initWithDict:dict];
}

@end

4. 視圖層:自訂 cell 並用 delegate 回傳事件

// YYappCell.h
@class YYappInfo, YYappCell;

// 協議命名慣例:類別名 + Delegate
@protocol YYappCellDelegate <NSObject>
- (void)btnDidClick:(YYappCell *)cell;
@end

@interface YYappCell : UITableViewCell
@property (nonatomic, strong) YYappInfo *app;
@property (nonatomic, strong) id<YYappCellDelegate> delegate;
@end
// YYappCell.m
@interface YYappCell ()
@property (weak, nonatomic) IBOutlet UIImageView *appimg;
@property (weak, nonatomic) IBOutlet UILabel     *apptitle;
@property (weak, nonatomic) IBOutlet UILabel     *appdownload;
@property (weak, nonatomic) IBOutlet UIButton    *appbtn;
@end

@implementation YYappCell

// 重寫 setter:模型一進來就更新畫面
- (void)setApp:(YYappInfo *)app {
    _app = app;
    self.apptitle.text   = _app.name;
    self.appdownload.text = [NSString stringWithFormat:@"大小 %@ | 下載量 %@次", _app.size, _app.download];
    self.appimg.image    = [UIImage imageNamed:_app.icon];
}

#pragma mark - 按鈕點擊:把事件交給代理
- (IBAction)btnOnclick:(UIButton *)sender {
    sender.enabled = NO;
    if ([self.delegate respondsToSelector:@selector(btnDidClick:)]) {
        [self.delegate btnDidClick:self];   // 誰觸發就把誰傳出去
    }
}

@end

5. 控制器層:當資料源,也當 cell 的代理

// YYViewController.m
@interface YYViewController () <UITableViewDataSource, YYappCellDelegate>
@property (nonatomic, strong) NSArray *apps;
@property (strong, nonatomic) IBOutlet UITableView *tableview;
@end

@implementation YYViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - 懶載入:讀 plist 並轉模型
- (NSArray *)apps {
    if (_apps == nil) {
        NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"apps_full.plist" ofType:nil];
        NSArray *arrayM = [NSArray arrayWithContentsOfFile:fullPath];

        NSMutableArray *models = [NSMutableArray arrayWithCapacity:arrayM.count];
        for (NSDictionary *dict in arrayM) {
            [models addObject:[YYappInfo appInfoWithDict:dict]];
        }
        _apps = [models copy];
    }
    return _apps;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.apps.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"app";   // 與 storyboard 上設定的 Reuse Identifier 一致
    YYappCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    cell.delegate = self;
    cell.app = self.apps[indexPath.row];
    return cell;
}

#pragma mark - YYappCellDelegate
- (void)btnDidClick:(YYappCell *)cell {
    YYappInfo *app = cell.app;

    UILabel *lab = [[UILabel alloc] init];
    lab.frame = CGRectMake(60, 300, 200, 20);
    lab.text = [NSString stringWithFormat:@"%@已經下載完成", app.name];
    [lab setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:lab];

    lab.alpha = 1.0;
    [UIView animateWithDuration:2.0 animations:^{
        lab.alpha = 0.0;
    } completion:^(BOOL finished) {
        [lab removeFromSuperview];
    }];
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

@end

這裡有個關鍵環節常被忽略:dequeueReusableCellWithIdentifier: 之所以能取到 storyboard 上的 cell,是因為在介面產生器裡已經為該 cell 打上了 Reuse Identifier(本例為 app)。標識字串對不上,取回來的就是 nil。

整体来看,動態單元格的價值在於「資料驅動畫面」:cell 的內容完全由模型決定,而 cell 內部的事件則透過 delegate 往上拋給控制器處理。這種分工讓列表能應付任意資料量,也是正式專案中的標準做法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved