2013-02-06 60 views
3

说我有一个表格中有10个静态单元格,有没有办法以编程方式选择某个单元格?UITableViewController以编程方式访问静态单元格问题

我已经试过这

UITableViewCell *cell = [self.tableView.subviews objectAtIndex:indexPath.row]; 

,但实际上并没有返回它似乎是一个表格单元格。

这似乎崩溃我的代码

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; 

我试着去设置单独的高度为在代码中静态细胞。一个选择是为每个单独的静态单元制作网点,但这看起来很愚蠢。

+0

你是什么意思的“静态细胞”?对于更普遍的答案:为什么你想直接访问单元格?你在代码中的哪个位置可以访问它? –

+0

UITabelViews可以具有在代码中生成的原型单元格,也可以在故事板(可选)中生成原型单元格,或者完全(通常)在故事板编辑器中生成的静态单元格,并且单元格数量不会变化 – Fonix

回答

13

要访问静态创建的细胞,试试这个:

UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; 

这适用于静态细胞。所以,如果你在...

- (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; 

    return cell; 

} 

...委托,你可以使用上面的声明访问所有静态配置的单元格。从那里,你可以做任何你想要的“细胞”。

我有一个ViewController,它有两个UITableViews。其中一个单元格具有静态定义的单元格,一个Storyboard,另一个单元格使用代码动态定义。鉴于我为这两个表使用相同的ViewController作为委托,我需要防止在调用cellForRowAtIndexPath的地方创建新的单元格,其中已经创建了单元格。

就你而言,你需要获得对你的单元格的编程访问权限。

玩得开心。

+0

嗨,我搜索遍布堆栈溢出广告找到你的解决方案。但是,我正在使用C#中的Xamarin.iOS。你有没有任何指针如何让这个工作Monotouch? – naffie

0

使用table view delegate方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSInteger height; 
    if(0 == indexPath.row) 
     { 
      height = 44; 
     } 
    else 
     { 
     height = 50; 
     } 
    return height; 
} 
+0

确实够好,回答我的问题,但如果我还想为单元格做其他事情呢?是否没有办法获得对实际单元格对象的引用? – Fonix

+2

Anil建议,您必须使用委托消息来更新您的单元格。如果你想在索引3重新加载单元格,你应该调用reloadRowsAtIndexPaths:消息传递该行,然后调用你的tableView:cellForRowAtIndexPath:消息。 –

+0

确定这可能是我需要的 – Fonix

1

你可以试试这个...

UITableViewCell *cell = (UITableViewCell*)[yourTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:rowvalue inSection:0]]; 
1

如果您需要接入小区物体,然后使用的UITableViewCell方法的cellForRowAtIndexPath是相当合适的。

这可能只是通过单元格,如果它是可见的,或调用你应该提供的委托方法cellForRowAtIndexPath(不要混淆它们)。如果那一个崩溃,那么深入挖掘并调查崩溃的根本原因。

5

创建一个@IBOutlet

即使您以编程方式重新排列静态单元格,这也可以工作。

+0

一直在寻找一段时间!这是解决这个问题的最佳解决方案。 –

0

这是一个Swift 2.3。解。

UITableViewController是在IB中创建的。

/* 
    NOTE 
    The custom static cells must be 
    In the IB tableview if one is being used 
    They also must be updated to be MYCustomTableViewCell 
    instead of UITableViewCell 
*/ 
import UIKit 

class MYCustomTableVC: UITableViewController 
{ 
    override func viewDidLoad() 
    { 
     super.viewDidLoad() 
     // NO Nib registration is needed 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    { 
     let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) as! MYCustomTableViewCell 
     // MYCustomTableViewCell can be created programmatically 
     // without a Xib file 
     return cell 
    } 
}