[英]Reuse error tableView with cell design programmatically
我的tableView由我特別管理的人有問題,我確實經常需要刪除和添加行。 我的單元是通過程序設計的。 我更新依賴於我的單元格的數組,並調用了self.tableView.reloadData()
但這不會刪除我需要的單元格並像我的數組一樣更新tableView。
導致單元重用和我的設計(以編程方式)的原因我需要檢查單元是否始終是設計的。 問題出在這里。
當我調用tableView.reloadData()
我的數據沒有正確地重新加載,因此我需要刪除單元格中的所有視圖:指示未設計單元格,以設計新的單元格...當然,我可以更新可見的單元格單元格(帶有tableView.visibleCells
),因此可以正常工作,但是如何更新其他不可見的單元格呢?
也許我有體系結構問題? 如果是這樣,在定義了indexPath的TableView中刪除和插入行的最佳方法是什么? 或者,如何僅一次以編程方式設計單元?
碼:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return user.lobbySurvey.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"Celll") as! CardCell
for survey in user.lobbySurvey{
let index = user.lobbySurvey.index(where: {
//get the current index is nedeed else the cells reuse lazy
$0 === survey
})
if indexPath.row == index{
var surveyState : UserSurvey.state
surveyState = survey.state
switch surveyState{
case .selectSurvey:
cell.drawCard(statutOfCard: .selectSurvey)
case .goSurvey:
cell.drawCard(statutOfCard: .goSurvey(picture: survey.picture))
case .surveyEnded:
print("survey Ended")
case .surveyWork:
print("survey in progress to vote")
case .surveyWaiting:
cell.drawCard(statutOfCard: .surveyWaiting(selfSurveyId: survey.id, timeLeft: survey.timeLeft, picture: survey.picture))
case .buyStack:
cell.drawCard(statutOfCard: .buyStack(supView : self.view))
}
}
}
cell.delegate = self
cell.delegateCard = self
cell.layer.backgroundColor = UIColor.clear.cgColor
cell.backgroundColor = .clear
tableView.backgroundColor = .clear
tableView.layer.backgroundColor = UIColor.clear.cgColor
return cell
}
您可以有一個數組,它是表的模型:
NSMutableArray *model;
(模型可以具有標識符)。
您可以隨時更改此模型。
有了這個,您可以使表動態化,只需調用tableView.reloadData()
並在cellForRow
和heightForRow
進行任何操作即可
- (CGFloat) tableView: (UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat height;
YourModel *model = self.model[indexPath.row];
if ([model isKindOfClass:[SomeClassTableViewCellModel class]]) {
height = 50;
} else if([model.identifier isEqualToString:@"Whatever"]){
height = 0.0f;
else{
height = kHeightForNormalCells;
}
return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
YourModel *model = self.model[indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:model.identifier forIndexPath:indexPath];
if ([cell isKindOfClass:[SomeClass class]]) {
NSLog(@"Configure Cell");
[cell setModel:model];
}
return cell;
}
此外,您的單元格應具有setModel方法:
- (void)setModel:(SomeTableViewCellModel *)model {
_model = model;
self.label1.text = [NSString stringWithFormat:@"%@",model.value1];
self.label2.text = [NSString stringWithFormat:@"%@",model.value2];
}
希望這對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.