xcode 以编程方式将 UITableViewCell 添加到 UITableView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17112177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding UITableViewCell programmatically to UITableView
提问by liv a
I have created a custom UITableViewCell programmatically and wish to add it to a UITableView of UITableViewController created in IB. How can I do that?
我以编程方式创建了一个自定义 UITableViewCell,并希望将其添加到在 IB 中创建的 UITableViewController 的 UITableView。我怎样才能做到这一点?
回答by iSmita
Try this -
尝试这个 -
In cellForRowAtIndexPath method add your custom cell like this -
在 cellForRowAtIndexPath 方法中添加您的自定义单元格,如下所示 -
static NSString *CellIdentifier = @"DashboardCell";
DashboardTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[DashboardTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
If cell contains image,text,etc then add like this -
如果单元格包含图像、文本等,则像这样添加 -
cell.image.image = [UIImage imageNamed:[apdelobj.array1_25 objectAtIndex:myInt]];
cell.titleLabel.text = dashboardList.mistohMessage;
回答by Valeriy Van
UITableViewDataSource
's delegate method -(UITableViewCell*)tableView:(UITableView*)t cellForRowAtIndexPath:(NSIndexPath*)indexPath
is just for that, no matter how cell was created, programmatically or in IB. Just return your created cell from this method. Don't forget to populate created cell with your data.
UITableViewDataSource
的委托方法-(UITableViewCell*)tableView:(UITableView*)t cellForRowAtIndexPath:(NSIndexPath*)indexPath
就是为了这个,无论单元是如何创建的,以编程方式或在 IB 中。只需从此方法返回您创建的单元格。不要忘记用您的数据填充创建的单元格。
So you have provide UITableViewDataSource
methods. Except mentioned above, this delegate has one more required method, -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
. Everything else is not necessary, but often useful. Consult UITableViewDataSource
protocol reference.
所以你提供了UITableViewDataSource
方法。除了上面提到的,这个委托还有一个需要的方法,-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
. 其他一切都不是必需的,但通常很有用。请参阅UITableViewDataSource
协议参考。