我在uitableviewcell上有一个按钮,其目标功能如下:
likeButton?.addTarget(self, action: "likeButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
在函数内部我设置了我的按钮标题:
sender.setTitle("\(addedLikeCount) Likes", forState: UIControlState.Normal)
但无论何时我向上或向下滚动视图,我的按钮标题都会更改为默认值。为什么会这样?有没有办法可以在不重新加载表的情况下解决这个问题?
随意给我任何建议,在迅捷或客观的c中无关紧要。
更新
所以我在我的函数下面编写了代码:
self.likeArray.replaceObjectAtIndex(index!, withObject: addedLikeCount)
sender.setTitle("\(self.likeArray[index!]) Likes", forState: UIControlState.Normal)
这是我的uitableviewcell:
var totalLike = likeArray[indexPath.row] as? String
currentLikeCount = totalLike
likeButton?.setTitle("\(totalLike)", forState: UIControlState.Normal)
它有效,但当我滚动时,tittle再次成为默认值
答案 0 :(得分:2)
Tableview单元格在滚动后每次显示在屏幕上时重新加载。 您必须在故事板或XIB上为您的单元格提供可重用的标识符 Objective-C变体:
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"your_cell_identifier_on_storyboard_or_cell_xib";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
/// datasource code here
return cell;
}
如果你想存储特定索引路径的所有上下文,就像你的问题一样 - 要保留所有按钮标题,请使用
dequeueReusableCellWithIdentifier: forIndexPath:
而不是
dequeueReusableCellWithIdentifier:
警告:为特定索引路径出列单元格可能会降低性能
答案 1 :(得分:1)
你在代码中使用它吗?
tableView.dequeueReusableCellWithIdentifier("reuseIdentifer")
如果是,则必须保存每个单元格的状态。
因为每次向上和向下滚动时,TableView都会返回屏幕外的上一个单元格。
您需要的是将单元格的新状态设置为与indexPath
方法中的cellForRowAtIndexPath
相对应
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifer") as? UITableViewCell{
cell.title = titles[indexPath.row]
return cell
}
...
...
}
答案 2 :(得分:0)
正如Oyeoj评论的那样
单元格正在发生变化,因为“单元格正在被重用,因此刷新到cellForRowAtIndexPath
下的原始设置,解决方案是设置一个全局变量,然后在cellForRowAtIndexPath
下重新加载时设置。”
对于您想要的任务,您必须将选定的单元格索引存储在某些位置,即someIndex
单元格上的按钮具有Likes
标题。
for Objective-C
in .h
NSMutableArray likeArray;
in .m
viewDidLoad
中的
likeArray=[[NSMutableArray alloc]init];
在cellForRowAtIndexPath
检查
if ([likeArray containObject:[NSNumber numberWithInteger:indexPath.row]])
{
[button setTitle:@"Likes", forState: UIControlStateNormal];
}
else
{
[button setTitle:@"Some Other Title", forState: UIControlStateNormal];
}
<{1>} - 中的
didSelectRowAtIndexPath
答案 3 :(得分:0)
创建一个函数,检查标题的哪一行被更改,反之亦然。例如
cufflinks/sliver-star
现在创建一个数组,用于存储更改标题的按钮,因此无论何时点击按钮,您都可以将其添加到-(BOOL)checkForSelectedRow:(NSIndexPath *)path
现在在
likeButtonTapped