您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 實作 tableView 點擊展開,並在內嵌 collectionView 中上傳圖片

編輯:iOS 相關教學

這個案例示範一個很常見的表單互動:列表的每一區塊可以點擊展開/收合,展開後的內容區塊裡內嵌一個 UICollectionView,用來挑選並預覽照片,點擊「立即上傳」時會跳出拍照或相簿選擇的提示框。

目標效果如下:

一、把 window 的根視圖控制器設為 UITableViewController

#import "AppDelegate.h"
#import "YCTableViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[YCTableViewController alloc] init]];
    [self.window makeKeyAndVisible];
    return YES;
}

@end

二、UITableViewController:展開收合與圖片選擇

先宣告需要的屬性。dataArray 存放各區塊的資料,每個 model 用一個 Is_Open 布林值記錄展開狀態;ownHobby 是一個「陣列的陣列」,每個區塊各自維護自己的照片清單。

#import <UIKit/UIKit.h>
#import "DepositFeeHeader.h"
#import "DepositFeeWithApplyTableViewCell.h"
#import "AppModel.h"
#import "MyCollectionViewCell.h"
#import "SectionHeaderViewCollectionReusableView.h"

#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define KScreenHeight [UIScreen mainScreen].bounds.size.height

@interface YCTableViewController : UITableViewController
<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,
 UIImagePickerControllerDelegate, UIActionSheetDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *ownHobby;   // 上傳圖片陣列
@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) UIActionSheet *actionSheet;
@property (nonatomic, assign) NSInteger reUpdate;
@property (nonatomic, assign) NSInteger number;           // 目前操作的分區索引

@end

資料源的關鍵在於:用 model 的展開狀態決定該 section 有幾行,收合時回傳 0,展開時回傳 1。

@implementation YCTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _dataArray = [[NSMutableArray alloc] initWithCapacity:1];
    for (int i = 0; i < 3; i++) {
        [_dataArray addObject:[[AppModel alloc] init]];
    }
    _ownHobby = [NSMutableArray array];
    _reUpdate = 10000;   // 賦初值,代表「目前沒有正在更新的分區」
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // 每個分區都配一個獨立的照片陣列
    [_ownHobby removeAllObjects];
    for (int i = 0; i < _dataArray.count; i++) {
        [_ownHobby addObject:[NSMutableArray array]];
    }
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    AppModel *model = _dataArray[section];
    return [model Is_Open] ? 1 : 0;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    AppModel *model = _dataArray[section];
    if (model.Is_Open == YES || section == _dataArray.count - 1) {
        return 0.01;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor whiteColor];
    return backView;
}

header 上放一個箭頭圖示,並依展開狀態旋轉它,讓使用者有明確的視覺回饋:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    DepositFeeHeader *depositHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"deposit"];
    if (depositHeader == nil) {
        depositHeader = [[DepositFeeHeader alloc] initWithReuseIdentifier:@"deposit"];
    }
    depositHeader.tag = 1000 + section;
    [depositHeader.tap addTarget:self action:@selector(showDetail:)];

    // 收合時 0 度,展開時旋轉 90 度
    AppModel *model = _dataArray[section];
    CGFloat rota = [model Is_Open] ? M_PI_2 : 0;
    [UIView animateWithDuration:0.1 animations:^{
        depositHeader.listImage.transform = CGAffineTransformMakeRotation(rota);
    }];

    return depositHeader;
}

// 點擊 header 切換展開狀態
- (void)showDetail:(UITapGestureRecognizer *)tap {
    AppModel *model = _dataArray[tap.view.tag - 1000];
    model.Is_Open = ![model Is_Open];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:tap.view.tag - 1000]
                  withRowAnimation:UITableViewRowAnimationNone];
}

展開後的 cell 中內嵌 collectionView:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == _reUpdate) {
        return nil;
    }

    DepositFeeWithApplyTableViewCell *cell = [[DepositFeeWithApplyTableViewCell alloc]
                                              initWithStyle:UITableViewCellStyleDefault
                                            reuseIdentifier:@"applyCell"];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 10);
    flowLayout.itemSize = CGSizeMake(40, 40);

    _collection = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 10,
                                                                    cell.backView.frame.size.width - 20,
                                                                    90)
                                    collectionViewLayout:flowLayout];
    _collection.tag = indexPath.section;   // 用 tag 記住自己屬於哪一區
    _collection.bounces = NO;
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.backgroundColor = [UIColor whiteColor];
    [_collection registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"identifier"];
    [cell.backView addSubview:_collection];

    [cell.shouldBtn addTarget:self action:@selector(upImage:) forControlEvents:UIControlEventTouchUpInside];
    cell.shouldBtn.tag = indexPath.row + 2000;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

三、照片來源選擇

上傳前先檢查數量上限,再依裝置是否支援相機決定要顯示哪些選項:

- (void)upImage:(UIButton *)btn {
    if ([_ownHobby[_number] count] == 9) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"上傳照片不能超過 9 張,點擊圖片可以刪除"
                                                                      message:@""
                                                               preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"確定"
                                                  style:UIAlertActionStyleDefault
                                                handler:nil]];
        [self.navigationController presentViewController:alert animated:YES completion:nil];
    } else {
        [self callActionSheet];
    }
}

- (void)callActionSheet {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"選擇照片"
                                                      delegate:self
                                             cancelButtonTitle:@"取消"
                                        destructiveButtonTitle:nil
                                             otherButtonTitles:@"拍照", @"從相簿選擇", nil];
    } else {
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"選擇照片"
                                                      delegate:self
                                             cancelButtonTitle:@"取消"
                                        destructiveButtonTitle:nil
                                             otherButtonTitles:@"從相簿選擇", nil];
    }
    [self.actionSheet showInView:self.tableView];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
            case 0: sourceType = UIImagePickerControllerSourceTypeCamera; break;
            case 1: sourceType = UIImagePickerControllerSourceTypePhotoLibrary; break;
            default: return;
        }
    } else {
        if (buttonIndex == 1) {
            return;
        }
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }

    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = sourceType;
    [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    [_ownHobby[_number] addObject:[info objectForKey:UIImagePickerControllerOriginalImage]];
    [_collection reloadData];
}

四、collectionView 的資料源與互動

這裡有個小技巧:永遠多留一格作為「+」的添加按鈕,因此項目數是 照片數量 + 1;而當 indexPath.row 等於照片數量時,就代表這一格是添加鈕。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    _number = collectionView.tag;

    if ([_ownHobby[_number] count] == indexPath.row) {
        // 最後一格:添加按鈕
        MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier"
                                                                              forIndexPath:indexPath];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                              action:@selector(textfiledShow)];
        cell.imageView.userInteractionEnabled = YES;
        [cell.imageView addGestureRecognizer:tap];
        cell.cellStyle = cellStyleAdd;
        cell.layer.borderWidth = 0;
        [cell layoutSubviews];
        return cell;
    }

    // 其餘各格:已選照片
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier"
                                                                          forIndexPath:indexPath];
    cell.photo.image = _ownHobby[_number][indexPath.row];
    cell.cellStyle = cellStyleSelected;
    [cell layoutSubviews];
    [cell.imageView removeFromSuperview];
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    return [_ownHobby[_number] count] + 1;
}

// 每個 item 大小
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(40, 40);
}

// 點擊已選照片即刪除
- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([_ownHobby[_number] count]) {
        [_ownHobby[_number] removeObjectAtIndex:indexPath.row];
        [_collection reloadData];
    }
}

@end

五、自定義 header 與 cell

header 用 UITableViewHeaderFooterView 子類實作,這樣才能用 dequeueReusableHeaderFooterViewWithIdentifier: 重用:

// DepositFeeHeader.h
@interface DepositFeeHeader : UITableViewHeaderFooterView
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *listImage;   // 尾部箭頭
@property (nonatomic, strong) UIGestureRecognizer *tap;
@end

// DepositFeeHeader.m
@implementation DepositFeeHeader

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithReuseIdentifier:reuseIdentifier];
    if (self) {
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        backView.backgroundColor = [UIColor whiteColor];
        [self addSubview:backView];

        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, kScreenWidth - 45, 20)];
        self.titleLabel.text = @"車輛押金";
        self.titleLabel.textColor = [UIColor grayColor];
        [backView addSubview:self.titleLabel];

        self.listImage = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth - 25, 10, 10, 20)];
        self.listImage.image = [UIImage imageNamed:@"jiantou.png"];
        [backView addSubview:self.listImage];

        // 上下分隔線
        UIImageView *headerLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
        headerLine.image = [UIImage imageNamed:@"line"];
        [backView addSubview:headerLine];

        UIImageView *footerLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 39, kScreenWidth, 1)];
        footerLine.image = [UIImage imageNamed:@"line"];
        [backView addSubview:footerLine];

        self.tap = [[UITapGestureRecognizer alloc] init];
        [self addGestureRecognizer:self.tap];
    }
    return self;
}

@end

cell 中比較特別的是「虛線框」,做法是用四個 UIImageView 分別畫上下左右四條虛線:

// DepositFeeWithApplyTableViewCell.m
@implementation DepositFeeWithApplyTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(20, 15, kScreenWidth - 40, 170)];
        [self addSubview:_backView];
        [self addDottedLineFromImageView:_backView];

        self.updatePresent = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 40, 20)];
        self.updatePresent.center = CGPointMake((kScreenWidth - 40) / 2, 110);
        self.updatePresent.text = @"點擊左上角按鈕添加照片";
        self.updatePresent.textColor = [UIColor lightGrayColor];
        self.updatePresent.textAlignment = NSTextAlignmentCenter;
        self.updatePresent.font = [UIFont systemFontOfSize:14];
        [_backView addSubview:self.updatePresent];

        self.shouldBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.shouldBtn.frame = CGRectMake((kScreenWidth - 40) / 2 - 45, 130, 90, 20);
        [self.shouldBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.shouldBtn setTitle:@"立即上傳" forState:UIControlStateNormal];
        self.shouldBtn.layer.cornerRadius = 5;
        self.shouldBtn.backgroundColor = [UIColor colorWithRed:18/255.0 green:129/255.0 blue:201/255.0 alpha:1];
        [_backView addSubview:self.shouldBtn];
    }
    return self;
}

// 添加虛線框
- (void)addDottedLineFromImageView:(UIView *)superView {
    CGFloat w = superView.frame.size.width;
    CGFloat h = superView.frame.size.height;
    CGFloat padding = 20;

    // 用四個 imageView 分別當上下左右四條邊
    for (NSInteger i = 0; i < 4; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.backgroundColor = [UIColor clearColor];
        if (i == 0) {
            imageView.frame = CGRectMake(0, 0, w, padding);
        } else if (i == 1) {
            imageView.frame = CGRectMake(0, 0, padding, h);
        } else if (i == 2) {
            imageView.frame = CGRectMake(0, h - padding, w, padding);
        } else {
            imageView.frame = CGRectMake(w - padding, 0, padding, h);
        }
        [superView addSubview:imageView];

        UIGraphicsBeginImageContext(imageView.frame.size);
        [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];

        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);   // 線條端點圓潤
        CGFloat lengths[] = {10, 5};   // 虛線的「實—虛」長度
        CGContextRef line = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(line, [UIColor blackColor].CGColor);
        CGContextSetLineDash(line, 0, lengths, 2);

        CGContextMoveToPoint(line, 0, 0);
        if (i == 0) {
            CGContextAddLineToPoint(line, w, 0);
        } else if (i == 1) {
            CGContextAddLineToPoint(line, 0, h);
        } else if (i == 2) {
            CGContextMoveToPoint(line, 0, padding);
            CGContextAddLineToPoint(line, w, padding);
        } else {
            CGContextMoveToPoint(line, padding, 0);
            CGContextAddLineToPoint(line, padding, h);
        }
        CGContextStrokePath(line);

        imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
}

@end

六、collectionView 的補充視圖與自定義 item

// SectionHeaderViewCollectionReusableView.m
@implementation SectionHeaderViewCollectionReusableView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createViews];
    }
    return self;
}

- (void)createViews {
    _titleLabel = [[UILabel alloc] init];
    [self addSubview:_titleLabel];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _titleLabel.frame = CGRectMake(20, 30, 375, 50);
    _titleLabel.font = [UIFont systemFontOfSize:20];
}

@end

item 用一個枚舉控制外觀,就能在同一個 cell 類別中同時處理「已選照片」與「添加按鈕」兩種樣式:

// MyCollectionViewCell.h
typedef enum : NSInteger {
    cellStyleDefault  = 0,
    cellStyleSelected = 1,
    cellStyleAdd      = 2,
} CollectionViewCellStyle;

@interface MyCollectionViewCell : UICollectionViewCell
@property (nonatomic, assign) CollectionViewCellStyle cellStyle;
@property (nonatomic, strong) UIImageView *photo;
@property (nonatomic, strong) UIImageView *imageView;
@end

// MyCollectionViewCell.m
@implementation MyCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _photo = [[UIImageView alloc] init];
        _imageView = [[UIImageView alloc] init];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [_photo setFrame:self.bounds];
    _imageView.frame = self.bounds;

    switch (_cellStyle) {
        case cellStyleDefault:
            self.layer.borderColor = [UIColor colorWithRed:0 green:0.68 blue:0.94 alpha:1].CGColor;
            self.layer.masksToBounds = YES;
            self.layer.borderWidth = 1.8;
            self.backgroundColor = [UIColor whiteColor];
            [self.contentView addSubview:_photo];
            break;

        case cellStyleSelected:
            self.layer.borderColor = [UIColor colorWithRed:0 green:0.68 blue:0.94 alpha:1].CGColor;
            self.layer.masksToBounds = YES;
            self.layer.borderWidth = 1.8;
            self.backgroundColor = [UIColor colorWithRed:0 green:0.68 blue:0.94 alpha:1];
            [self.contentView addSubview:_photo];
            break;

        case cellStyleAdd:
            [_imageView setImage:[UIImage imageNamed:@"addPhoto.png"]];
            self.backgroundColor = [UIColor whiteColor];
            [self.contentView addSubview:_imageView];
            break;

        default:
            break;
    }
}

@end

七、model

// AppModel.h
@interface AppModel : NSObject
@property (nonatomic, assign) BOOL Is_Open;
@end

// AppModel.m
@implementation AppModel
@end

之所以要獨立一個 model,就是為了用一個布林值記錄每個分區的展開狀態,再據此呼叫 reloadSections:withRowAnimation: 完成展開與收合的動畫。

這個案例的幾個關鍵設計值得記下來:

  • 用 model 的狀態驅動行數,而不是直接操作 tableView 的 frame 或高度,這樣資料與界面保持一致。
  • 用 tag 標記 collectionView 所屬的分區,是解決「多個 collectionView 共用一個 delegate」的常用手法。
  • 照片陣列用「陣列的陣列」分區存放,並在 numberOfSectionsInTableView: 中重建,確保每個分區各自獨立。
  • item 數固定多一格作為添加鈕,用 indexPath.row == count 判斷,讓「預覽」與「添加」共用同一套資料源邏輯。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved