假设我有一个包含10个静态单元格的表格,有没有办法以编程方式选择某个单元格?
我试过这个
UITableViewCell *cell = [self.tableView.subviews objectAtIndex:indexPath.row];
但实际上并没有返回表格单元格。
这似乎导致我的代码崩溃
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
我试图在代码中设置静态单元格的各个高度。一个选择是为每个静态单元格制作出口,但这看起来很愚蠢。
答案 0 :(得分:15)
要访问静态创建的单元格,请尝试以下操作:
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已经创建了单元格。
在您的情况下,您需要以编程方式访问您的单元格。
玩得开心。
答案 1 :(得分:7)
创建@IBOutlet
。
即使您以编程方式重新排列静态单元格,这也会有效。
答案 2 :(得分:1)
你可以试试这个......
UITableViewCell *cell = (UITableViewCell*)[yourTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:rowvalue inSection:0]];
答案 3 :(得分:1)
如果需要访问单元格对象,那么使用UITableViewCell方法cellForRowAtIndexPath是非常合适的。
这可能只是传递单元格,如果它是可见的,或者调用你应该提供的委托方法cellForRowAtIndexPath(不要混淆)。如果那个崩溃,那么深入挖掘并调查崩溃的根本原因。
答案 4 :(得分:0)
使用table view delegate
方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger height;
if(0 == indexPath.row)
{
height = 44;
}
else
{
height = 50;
}
return height;
}
答案 5 :(得分: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
}
}