为什么 cell tag returns 与 UITableView 中的值相同?
Why cell tag returns the same value in UITableView?
在我的 cellForRowAtIndexPath 中,我将标签添加到我的单元格中:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:people = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! people
cell.fullName.text = self.fullNames[indexPath.row]
cell.viewProfile.tag = indexPath.row
temp = cell.viewProfile.tag
cell.viewProfile.addTarget(self, action: "viewProfile:", forControlEvents: .TouchUpInside)
return cell
}
其中
var temp = 0
在顶部,在 class 声明下。
当我稍后尝试时:
func viewProfile(sender: UIButton) {
print(temp)
}
它returns我2,每次都一样的值。为什么?我做错了什么?
如果您正在尝试获取被单击按钮的索引。然后试试这个
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:people = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! people
cell.fullName.text = self.fullNames[indexPath.row]
cell.viewProfile.tag = indexPath.row
cell.viewProfile.addTarget(self, action: "viewProfile:", forControlEvents: .TouchUpInside)
return cell
}
func viewProfile(sender: UIButton) {
print("Index : \(sender.tag)")
}
不需要临时变量。
我认为您应该覆盖方法 didSelectRowAtIndexPath 以显示 indexPath.row。您总是打印相同的值,因为在您 运行 cellForRowAtIndexPath 的情况下,它总是 运行 直到最后一个单元格显示在您的视图中。所以你总是得到相同的临时变量值。
在我的 cellForRowAtIndexPath 中,我将标签添加到我的单元格中:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:people = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! people
cell.fullName.text = self.fullNames[indexPath.row]
cell.viewProfile.tag = indexPath.row
temp = cell.viewProfile.tag
cell.viewProfile.addTarget(self, action: "viewProfile:", forControlEvents: .TouchUpInside)
return cell
}
其中
var temp = 0
在顶部,在 class 声明下。
当我稍后尝试时:
func viewProfile(sender: UIButton) {
print(temp)
}
它returns我2,每次都一样的值。为什么?我做错了什么?
如果您正在尝试获取被单击按钮的索引。然后试试这个
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:people = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! people
cell.fullName.text = self.fullNames[indexPath.row]
cell.viewProfile.tag = indexPath.row
cell.viewProfile.addTarget(self, action: "viewProfile:", forControlEvents: .TouchUpInside)
return cell
}
func viewProfile(sender: UIButton) {
print("Index : \(sender.tag)")
}
不需要临时变量。
我认为您应该覆盖方法 didSelectRowAtIndexPath 以显示 indexPath.row。您总是打印相同的值,因为在您 运行 cellForRowAtIndexPath 的情况下,它总是 运行 直到最后一个单元格显示在您的视图中。所以你总是得到相同的临时变量值。