【发布时间】:2016-09-28 11:01:01
【问题描述】:
我在情节提要中创建了一个 tableview 原型单元格,并向单元格添加了一个按钮并将其标记设置为 indexpath.row。当我滚动我的单元格时,tableview 顶部的滚动单元格总是将标签设置为零而不是正确的标签。
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("autoLoadReuseIndentifier", forIndexPath: indexPath)
print("indexpath :\(indexPath.row)")
cell.contentView.viewWithTag(100)?.layer.cornerRadius = 5
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
let tempDict : NSDictionary = savedCardsArray.objectAtIndex(indexPath.row) as! NSDictionary
let bankName = cell.contentView.viewWithTag(102) as! UILabel
deleteButton = cell.contentView.viewWithTag(106) as? UIButton
deleteButton?.tag = indexPath.row
deleteButton?.addTarget(self, action: "deleteCard1:", forControlEvents: UIControlEvents.TouchUpInside)
print("delete button:\(deleteButton)")
// print("indexpath delete tag :\(deleteButton.tag)")
if(self.isSetUpAutoloadSelected){
deleteButton?.hidden = true
}else{
deleteButton?.hidden = false
}
return cell;
}
每当我滚动单元格时,删除按钮标签总是设置为零。
【问题讨论】:
-
哪个视图有标签 100、102 和 106。请为每个视图命名。
-
显示
print("delete button:\(deleteButton)")的日志 -
在我之后重复“不要使用标签。它们很脆弱。它们会给我带来比它们解决的问题更多的问题”。使用具有属性的正确
UITableViewCell子类来引用您的视图。使用协议和委托将按钮事件从单元格返回到您的视图控制器。让单元格将自身传递给委托,以便视图控制器可以识别行 -
@Paulw11 是对的,顺便说一句,您是否创建了自定义
UITableViewCell类并将其分配给单元格? -
请参阅stackoverflow.com/questions/28659845/…,了解使用从单元格到视图控制器的协议的示例。该问题的另一个答案显示了如何使用闭包,这是另一种好方法
标签: ios objective-c swift xcode tableview