如何使用Delegate方法知道在哪个单元格中按下按钮。迅速

时间:2015-08-09 05:15:25

标签: ios swift uitableview uibutton

所以我有userListTableViewControlleruserListTableViewCell我正在连接followButton ..这是我userListTableViewCell的代码

import UIKit

class userListTableViewCell: UITableViewCell {

// IBOutlets..


@IBOutlet var followButton: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

    func createButton(delegate:AnyObject){

    followButton.addTarget(delegate, action: "followButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)


  }

 }

这是我的cellForRowAtIndexPath代码:

myCell.createButton(self)

这是followButtonTapped

userListTableViewController的功能
 func followButtonTapped(object:AnyObject) {



    println("button clicked") // ******************** here i want to know in which cell or indexPath the button is being pressed. or maybe when button is being tapped, change the title of that button.


}

我需要一些很好的解释,我已经标记了" ******************"。谢谢你的时间。

3 个答案:

答案 0 :(得分:0)

我抓住NSIndexPath的任何单元格,并在cellForRow分配。

在委托方法中,我正在返回单元格本身, (请参阅UITableView委托函数 - 它们提供UITableView),因此在委托函数中您拥有相关的单元格,并且它具有相关的NSIndexPath

注意 - 如果你指定NSIndexPath - 任何细胞的变化,如添加行或删除一个将使其他单元格的旧NSIndexPath不正确...

答案 1 :(得分:0)

将按钮标记设置为cellForRowAtIndexPath代码中的indexPath.row,并将followButtonTapped方法设置为@IBAction,其参数为UIButton,而不是{{ 1}}

所以在AnyObject添加此内容:

cellForRowAtIndexPath

并将您的myCell.followButton.tag = indexPath.row 方法更改为:

followButtonTapped

您必须将@IBAction func followButtonTapped (sender: UIButton!) { println("\(sender.tag) button pressed") } 连接到IB中的关注按钮,但之后应该很高兴。

答案 2 :(得分:-1)

单击单元格时调用TableView didSelectRowAtIndexPath函数。

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
相关问题