这是我的代码:
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?
}
我希望能够打印变量用户名,但是当我按下按钮时它为单元格打印了错误的用户名。为什么会这样,我该如何解决?
最佳答案
在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
}
获取 Action 为
func tapButton(sender: UIButton!)
{
username = sender.titleLabel.text
print(username)
}
关于ios - 从单元格中获取标签 - swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38929376/