65 uitableview ios
我在每个部分都有n个部分(已知数量)和X行(未知数量.每行都有一个UITextField.当用户点击"完成"按钮时,我想迭代每个单元格并使用UITextField进行一些条件测试.测试传递来自每个单元格的数据被写入数据库.如果没有,则显示UIAlert.循环遍历行的最佳方法是什么,如果有更优雅的解决方案,请建议.
Pau*_*tin 162
如果您只想迭代可见单元格,请使用
NSArray *cells = [tableView visibleCells];
Run Code Online (Sandbox Code Playgroud)
如果你想要表视图的所有单元格,那么使用这个:
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
{
for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
{
[cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以遍历所有单元格:
(CustomTableViewCell是一个类,它包含UITextField类型的属性textField)
for (CustomTableViewCell *cell in cells)
{
UITextField *textField = [cell textField];
NSLog(@"%@"; [textField text]);
}
Run Code Online (Sandbox Code Playgroud)
小智 13
这是一个适合我的快速实现.
func animateCells() {
for cell in tableView.visibleCells() as! [UITableViewCell] {
//do someting with the cell here.
}
}
Run Code Online (Sandbox Code Playgroud)
对于那些不了解ObjC的人(像我一样),swift接受的答案.
for section in 0 ..< sectionCount {
let rowCount = tableView.numberOfRowsInSection(section)
var list = [TableViewCell]()
for row in 0 ..< rowCount {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) as! YourCell
list.append(cell)
}
}
Run Code Online (Sandbox Code Playgroud)
对于 xcode 9 使用此 - (类似于@2ank3th,但代码已针对 swift 4 进行了更改):
let totalSection = tableView.numberOfSections
for section in 0..<totalSection
{
print("section \(section)")
let totalRows = tableView.numberOfRows(inSection: section)
for row in 0..<totalRows
{
print("row \(row)")
let cell = tableView.cellForRow(at: IndexPath(row: row, section: section))
if let label = cell?.viewWithTag(2) as? UILabel
{
label.text = "Section = \(section), Row = \(row)"
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64571 次 |
| 最近记录: |