[英]Get hidden value from Cell in TableView
我想用数据库中的数据填充 TableView,当点击单元格时,在didSelectRowAtIndexPath
,将选定的ID
发送到新视图。
我想在单元格文本中查看记录的描述并将ID
放在单元格的隐藏字段/属性中,但我找不到方法。 我知道我可以从数据源获取一个ID
(类似于[my_data_source objectAtIndex:indexPath.row];
),但我不太喜欢这种方式,我更喜欢将ID
分配给单个单元格。
有没有办法做到这一点?
提前致谢和问候。
我猜你来自网络开发? 我也发现这样做很困难,但这是最好的方法。 它可能是可能的 - 但如果你习惯这样做会更好,它确实如此。
基本上在 .h 文件中定义一个 NSArray(所以整个脚本都可以使用它)。
然后在 init 函数中:
// set the array
myArray = [NSArray arrayWithObjects:@"One",@"Two",@"Threee",nil];
[myArray retain];
然后是表视图委托方法:
// set numebr of rows
- (CGFloat)tableView:(UITableView *)tableView numberOfRowsForSection:(NSUInteger)section {
return [myArray count];
}
// set the cell titleLabel value
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// set the cell - I can't remember the exact code then do:
cell.textLabel.text = [myArray objectAtIndex:[indexPath row]];
}
// similarly
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"%@",[myArray objectAtIndex:[indexPath row]];
}
(免责声明:这些只是我的头脑,我还没有检查确切的方法 - 它们可能在某些方面是错误的 - 但函数中的代码正是你真正想要的。)
当您开始使用它时,您会发现它比在表格中的某处“隐藏”一个 id 好得多。 要从数据库中获取内容,我建议将其全部添加到字典、数组或类似内容中,并在您初始化类时这样做,但如果您真的想动态地执行此操作,则假装您的“隐藏”ID 只是数组的索引。 所以 id#1 位于数组中的索引 1 处。 :)
好吧,这是对不同方法的快速破解。 我总是喜欢处理自包含的对象。 将您想要的所有数据打包到一个自定义类(此处称为MyData
)中,以便您使用您需要的最少数量对其进行初始化。 您从数据库中提取的 id 和文本。 您还实现了一个可以从数据库加载其余数据的函数。
当项目被选中时,您将对象的实例传递给子视图控制器并从数据库中填充其数据。 可以在主viewcontroller或者subviewcontroller触发填充,没关系。
主要的一点是将所有的数据打包到一个对象中(基本上是一个“模型”,你已经有了一个视图和控制器),然后通过访问该对象来填充视图。 这使您的界面在整个应用程序中始终保持不变。 并使更改更容易。 例如,如果您发现最好在程序开始时填写数据库中的所有数据,您现在可以这样做而无需更改其他视图。
@interface MyObject : NSObject
{
}
// Create a stump object that contains only the necessary info
+ (id) withName:(NSString)name id:(int)id;
// loads the rest of your data from the DB
- (void) fillFromDb;
@property (readwrite, retain) NSString name;
@property (readwrite, assign) int id;
// The data fields that you need
@end
// in tableview controller
@interface MyTableViewController ...
{
NSMutableArray _dbData;
}
@end
@implementation MyTableViewController
- (void) viewDidLoad {
// Load your data from DB
for (int i =0; i < dbCount; ++i)
{
MyObject* data = [MyObject withName:dbName[i] id:dbId[i];
[_dbData addObject:data];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell.textLabel.text = [_dbData objectAtIndex:[indexPath row]];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//Create Subviewcontroller
// Optional call fillFromDb here and not in subviewcontroller
subviewcontroller.dbData = [_dbData objectAtIndex:[indexPath row]];
//activate subview
}
@interface SubViewController {
MyObject* _dbData;
}
@end
@implementation SubViewController
- (void) viewDidLoad {
[_dbData fillFromDb];
// Do View Initialisations with the newly fetched Data
}
代码在这里只是为了演示架构
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.