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

自訂 UITableViewCell 按鈕點擊的三種處理方式

編輯:iOS 開發綜合

自訂 cell 上的按鈕點擊怎麼處理,是專案中反覆出現的需求。常見有三種做法,各有適用範圍。

方法一:給 Button 加上 tag

最直接的做法是在 cell 中建立按鈕並設定 tag,然後在控制器的方法裡用 tag 反查資料。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    User *user = _users[indexPath.row];
    cell.user = user;
    //拍照button
    UIButton *photographButton = [UIButton buttonWithType:UIButtonTypeCustom];
    photographButton.frame = CGRectMake(221 , 10, 100, 44);
    [photographButton setImage:[UIImage imageNamed:@"camera.png"] forState:UIControlStateNormal];
    [photographButton addTarget:self action:@selector(photographButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    photographButton.tag = indexPath.row;
    [cell.contentView addSubview:photographButton];
    return cell;
}

點擊時用 sender.tag 取回對應資料:

- (void)photographButtonClicked:(UIButton *)sender{
    User *user = _users[sender.tag];
    PhotoPickerController *photoPicker = [[PhotoPickerController alloc] init];
    photoPicker.user = user;
    [self.navigationController pushViewController:photoPicker animated:YES];
}

這種寫法有個隱患:cell 會被重用,如果在 cellForRow 中每次都 addSubview 一個新按鈕,滾動幾次後按鈕會層層堆疊。正確做法是在建立 cell 時一次加好,reuse 時只更新 tag 與顯示內容。

方法二:在自訂 Cell 中定義代理

#import <UIKit/UIKit.h>

@protocol TermCellDelegate <NSObject>
- (void)choseTerm:(UIButton *)button;
@end

@interface TermCell : UITableViewCell
@property (retain, nonatomic) IBOutlet UIButton *checkButton;
@property (retain, nonatomic) IBOutlet UILabel *termLabel;
@property (assign, nonatomic) BOOL isChecked;
@property (assign, nonatomic) id<TermCellDelegate> delegate;
- (IBAction)checkAction:(UIButton *)sender;
@end

#import "TermCell.h"

@implementation TermCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if (_isChecked) {
        [_checkButton setBackgroundImage:[UIImage imageNamed:@"task_state_checked"] forState:UIControlStateNormal];
    } else {
        [_checkButton setBackgroundImage:[UIImage imageNamed:@"task_state_unchecked"] forState:UIControlStateNormal];
    }
}

- (void)dealloc {
    [_checkButton release];
    [_termLabel release];
    [super dealloc];
}

- (IBAction)checkAction:(UIButton *)sender {
    if ([_delegate respondsToSelector:@selector(choseTerm:)]) {
        sender.tag = self.tag;
        [_delegate choseTerm:sender];
    }
}

@end

控制器側實作代理即可:

#pragma mark - TermCellDelegate
- (void)choseTerm:(UIButton *)button {
    _clickIndex = button.tag;
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"確定修改學期嗎?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
    [alertView show];
}

補充一個更省事的做法:直接把 cell 本身傳回代理方法,這樣不必再透過 tag 去陣列取資料,直接用 cell 上的資料物件就好。

方法三:在 Cell 內部直接跳轉

這種方式耦合度較高,思路是先找到 button 所屬的控制器,再執行跳轉。關鍵工具方法是沿著 responder chain 往上找:

#import "UIView+Additions.h"

@implementation UIView (Additions)

- (UIViewController *)viewController {
    UIResponder *next = [self nextResponder];
    do {
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = [next nextResponder];
    } while (next != nil);
    return nil;
}

@end

搭配 Block 使用時機寫法如下:

- (void)setWeiboModel:(WeiboModel *)weiboModel {
    if (_weiboModel != weiboModel) {
        [_weiboModel release];
        _weiboModel = [weiboModel retain];
    }
    __block WeiboCell *this = self;
    _userImage.touchBlock = ^{
        NSString *nickName = this.weiboModel.user.screen_name;
        UserViewController *userCtrl = [[UserViewController alloc] init];
        userCtrl.userName = nickName;
        [this.viewController.navigationController pushViewController:userCtrl animated:YES];
        [userCtrl release];
    };
}

這裡在賦值 model 的同時設定點擊行為,cell 自己就能完成跳轉。

三種方式該怎麼選?方法一適合簡單場景,但務必注意 cell 重用帶來的 tag 與子視圖堆疊問題;方法二是職責最清晰的方案,cell 只負責把事件往上拋,控制器決定怎麼反應,也最容易測試;方法三寫起來快,但把導航邏輯塞進 view 層,日後要複用到不同上下文時會很痛苦,不建議在大型專案中使用。

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