这是我的代码:
var username: String!
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell
username = usernameLabel.text
cell.button.userInteractionEnabled = true
let tapButton = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapLabel(_:)))
cell.button.addGestureRecognizer(tapButton)
return cell as MainCell
}
func tapButton(sender:UITapGestureRecognizer) {
print(username) //this prints the wrong cell... why?
}
我希望能够打印变量用户名,但是当我按下按钮时,它会打印出错误的用户名。为什么会这样,我该如何解决?
答案 0 :(得分:1)
在cellForRowAtIndex中添加标记
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : MainCell! = tableView.dequeueReusableCellWithIdentifier("MainCell") as! MainCell
cell.button.userInteractionEnabled = true
cell.button.setTitle( usernameLabel.text, forState: .Normal)
cell.button.tag = indexPath.row
cell.button.addTarget(self, action: #selector(ViewController.tapButton(_:)), forControlEvents: .TouchUpInside)
return cell as MainCell
}
采取行动
func tapButton(sender: UIButton!)
{
username = sender.titleLabel.text
print(username)
}
答案 1 :(得分:1)
你应该在MainCell中实现动作按钮。你有用户名,这是最好的做法;)
class MainCell: UITableViewCell {
@IBOutlet weak var usernameLabel: UITextView!
func tabButton(sender: AnyObject) {
print(usernameLabel.text)
}
}
答案 2 :(得分:0)
它将打印latest value
中存储的username
,因为每indexPath
个单元格,它都会更新username
&无论您是latest updated value
tapping
答案 3 :(得分:0)
1)在您的cellForRowAtIndexPath:方法中,将按钮标记指定为索引:
cell.yourbutton.tag = indexPath.row;
2)为按钮添加目标和操作,如下所示:
cell.yourbutton.addTarget(self, action: #selector(self.yourButtonClicked), forControlEvents: .TouchUpInside)
3)ViewControler中基于索引的代码操作:
func yourButtonClicked(sender: UIButton) {
if sender.tag == 0 {
// Your code here
}
}