[英]Reusable UITableView's prototype cell
我想创建一个原型单元格,可以通过故事板在不同的表格视图中使用..这样做的正确方法是什么? 任何指针赞赏。
我认为您不能创建原型单元并在故事板中的表之间共享它,但您可以在nib中创建原型单元,然后在ViewDidLoad方法中加载它,然后在表视图中使用它。 这真的很简单,这里是如何......
A.添加nib文件:
1.选择新文件... 2.选择IOS - >用户界面
3.选择“清空” - >这将向项目添加新文件.xib文件
4.将UITableViewCell从对象浏览器拖到xib文件中,并根据自己的喜好进行自定义
5.使用“实用工具”窗格更改属性 - >编辑笔尖与编辑故事板非常相似。
6.确保命名您的单元格 - 我选择了名称cellFromNib,但您可能还需要其他东西。
B.在每个表的viewDidLoad方法中加载UITableViewCell:
- (void)viewDidLoad
{
// load the cell in the nib - the nib can only contain this one UITableViewCell
[self.tableView
registerNib:[UINib nibWithNibName:[self @"nibFileNameWithoutExtension"]
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:[self @"cellFromNib"]];
}
C.将nib的tableViewCell排队...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellFromNib" forIndexPath:indexPath];
// customize your cell here...
}
D.在故事板中为TableView添加一个“虚拟”原型单元格。 在选择单元格时,将这个“虚拟”单元格中的segue设置为要显示的视图 - 确保命名segue - 我将其称为@“theSegue”。 您将在代码中引用此segue。
E.最后,添加代码以从该单元格中删除...
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// this is basically what the storyboard does under the hood...
// make sure you have a "dummy" prototype cell with this segue name for each
// tableview that uses this cell
[self performSegueWithIdentifier:@"theSegue" sender:self];
}
如果要专门化单元代码,请创建一个子类UITableViewCell的类
我认为这就是你需要的一切。
我会说不要害怕做这样的事情,因为如果你认真对待IOS编程,你会学到新东西。 它确实可以提供更好的可重用代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.