在寫項目布局的時候會有這么一種情況
或者
這種頁面 是單一的頁面,別的地方也用不到,, 用xib寫的話 cell就需要注冊好幾個。看起來挺多的,實際上有種方法能不用創建那么多的xib。
那就是在一個xib中創建多個cell
第一步創建
第二步 設置identifier
把每個cell 都設置成 相應的id之后
在tableView中
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *identifier = @"";//對應xib中設置的identifier NSInteger index = 0; //xib中第幾個Cell switch (indexPath.row) { case 0: identifier = @"0"; index = 0; break; case 1: identifier = @"1"; index = 1; break; case 2: identifier = @"2"; index = 2; break; default: break; } TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; if (!cell) { cell = [[[NSBundle mainBundle] loadNibNamed:@"TestTableViewCell" owner:self options:nil] objectAtIndex:index]; } return cell; }
注冊 cell 之后運行 沒bug之后 xib 創建多個cell就完成了
===============================華麗的分割線=======================================
這個操作完成之后 我們在cell上添加button
我們想做的操作是 點擊cell上的button 把button的title 打印出來。
其實有好多方法 通過屬性添加點擊事件 cell.button 或者 通過tag值找到button
還有一種在控制器里面很省代碼的方法
在TestTableViewCell.h中 寫個代理
#import <UIKit/UIKit.h> @protocol TestTableViewCellDelegate <NSObject> - (void)testBtn:(UIButton*)btn; @end @interface TestTableViewCell : UITableViewCell @property (nonatomic, weak)id <TestTableViewCellDelegate> testdelegate; @end
在TestTableViewCell.m中 加一個判斷
- (IBAction)textButton:(id)sender { if (self.testdelegate && [self.testdelegate respondsToSelector:@selector(testBtn:)]) { [self.testdelegate testBtn:sender]; } }
接着在你的controller中 添加代理
cell.testdelegate = self;
實現方法
- (void)testBtn:(UIButton *)btn { NSLog(@"%@", btn.titleLabel.text); }