2013-12-22 152 views
3

我有一个表视图的iOS的TableView如何访问自定义单元格变量

- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    **NSString *channelID = [object objectForKey:@"channelID"];** 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell==nil) 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle 
            reuseIdentifier:CellIdentifier]; 

} 

我访问的tableview细胞像这样:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 
    for (NSIndexPath *path in [tableView indexPathsForVisibleRows]) { 
     UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:path]; 
    } 
    //I want to access cell.ChannelID // 
} 

我如何可以访问的channelID变量? 当用户停止滚动时,我想访问可见的单元格和自定义变量。

谢谢

+0

什么是“对象”? – Moxy

回答

0

您确定channelID是UITableViewCell的成员吗?如果您已经声明UITableViewCell并使用您自己的自定义tableview单元格,则要使用该类别

4

如果您想要定制UITableView单元格,则需要创建UITableView单元格的子类。从那里,你需要在这个自定义单元上为你的对象声明一个属性。确保这个属性是公开的。从我在你的代码中看到的,它应该可能是这样的。

@interface MyCustomCell : UITableViewCell 

@property (strong, nonatomic) NSDictionary *myObject; 

@end 

从那里,你要的细胞亚类的头导入到你的表视图的委托/数据源的方法使用实现文件和而不是引用的UITableViewCell内的cellForRowAtIndexPath:引用您的子类,然后设置一个值给你新增加的属性。

- (MyCustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (!cell) { 
     cell = [[MyCustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    NSString *channelID = [cell.myObject objectForKey:@"channelID"]; 

    [cell.textLabel setText:channelID]; 

    return cell; 
} 

当然,不言而喻,你首先需要提供逻辑来传播这本词典。然后就滚动视图委托方法而言,你有类似的问题。您无法访问UITableViewCell基类上的自定义对象。你再次需要引用你的子类。这可以通过简单的演员轻松完成。

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 
    for (NSIndexPath *path in [tableView indexPathsForVisibleRows]) { 
     MyCustomCell *cell = (MyCustomCell *)[self.tableView cellForRowAtIndexPath:path]; 

     NSString *channelID = [cell.myObject objectForKey:@"channelID"]; 
     // 
    } 
} 
1

0x7fffffff答案有效。您也可以使用此功能并跳过空检查。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath]; 

    NSString *channelID = [cell.myObject objectForKey:@"channelID"]; 

    [cell.textLabel setText:channelID]; 
} 

但你必须声明什么是“CustomCell”是在viewDidLoad中注册它,否则你会得到一个异常:因为它使dequeueReusableCellWithIdentifier: forIndexPath:是保证返回

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [self.tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"]; 
} 

我喜欢这个更好细胞,并使cellForRowAtIndexPath有点清洁。但是,或者也可以。

+0

谢谢你....你救了我的一天.. –

相关问题