У меня есть UIViewController, в котором я планирую разместить два TableViews и некоторые другие элементы. Оба TableViews я использую на других экранах, поэтому я хочу сделать их как можно более независимыми и повторно используемыми.Один из этих TableViews называется messageList (UITableView), который показывает мою ChatHistory.
Я пытаюсь понять, подходит ли мой подход.[Отредактировано 9/2 с правильным кодом, чтобы этот подход работал]
Один из подходов состоит в том, чтобы использовать одну таблицу с 2 различными разделами, а затем в методах делегатов использовать условный оператор, чтобы увидеть, какой раздел какой иДействуй соответственно.
Проблема этого подхода заключается в удобстве использования.Я хочу легко повторно использовать мои TableViews в других представлениях, где один или другой TableView может существовать или не существовать.Кроме того, я хочу, чтобы источник данных существовал на протяжении всего жизненного цикла приложения, независимо от того, какой контроллер создан или активен.
Мой подход заключается в том, чтобы отделить контроллер представления, который управляет представлениями таблицы, от реализаций таблицы UITableViewDataSource и UITableViewDelegate.Но у меня проблема с выполнением этой работы.
Сосредоточение внимания на одном из TableViews, моем ChatTableView.
В моем AppDelegate есть свойство для chatHistory типа ChatHistory, которое реализует UITableViewDelegate & UITableViewDataSource.
// AppDelegate.h
ChatHistory *chatHistory;
...
@property (nonatomic, retain) ChatHistory *chatHistory;
// ChatHistory.h
#import <Foundation/Foundation.h>
@interface ChatHistory : NSObject <UITableViewDelegate, UITableViewDataSource> {
UITableViewCell *nibLoadedCell;
NSMutableArray *messages;
}
@property (nonatomic, retain) UITableViewCell *nibLoadedCell;
@property (nonatomic, retain) NSMutableArray *messages;
@end
// ChatHistory.m - Обратите внимание, этот код, включая пользовательскую ячейку, работал правильно, когда она была частью контроллера, поэтому я считаю, что она должна быть правильной
#import "ChatHistory.h"
#include "ChatMessage.h"
@implementation ChatHistory
@synthesize nibLoadedCell; // custom cell design
@synthesize messages;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [messages count];
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
return [NSString stringWithFormat:@"Discussion"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"ChatTableCell" owner:self options:nil];
cell = nibLoadedCell;
}
// custom tag order - username; message; future - Avatar; like; dislike
ChatMessage *obj = [messages objectAtIndex:indexPath.row];
UILabel *messageLabel = (UILabel *) [cell viewWithTag:1];
messageLabel.text = obj.message;
UILabel *usernameLabel = (UILabel *)[cell viewWithTag:2];
usernameLabel.text = obj.sender;
return cell;
}
- (void)dealloc {
if (messages) [messages release];
[super dealloc];
}
@end
//MyViewController.m
- (void)viewDidLoad { // MAKE SURE TO INITIALIZE viewDidLoad not InitWithNib
if (!appDelegate.chatHistory)
appDelegate.chatHistory = [[ChatHistory alloc] init];
messageList = [[UITableView alloc] initWithFrame:CGRectMake(0, 54, 320, 100) style:UITableViewStylePlain];
messageList.dataSource = appDelegate.chatHistory;
messageList.delegate = appDelegate.chatHistory;
[self.view addSubview:messageList];
...