View tableview cell text on table view cell button

2019-07-13 10:38发布

I have a table view where I have created a label and two buttons. I am stuck while getting the text from the label on button click. I have created an array list like:

let arrayList: [String] = [ "aaa" , "bbb" , "ccc"]

I want if I click the button on index[0] I shall get "aaa" and if index[2] I shall get "ccc"

enter image description here

@IBOutlet weak var titleLable: UILabel!
@IBOutlet weak var infoButton: UIButton!

myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: "buttonClicked", forControlEvents: .TouchUpInside)

3条回答
我命由我不由天
2楼-- · 2019-07-13 11:25

Try to get indexPath, where the button is clicked using the Button Tag.

@IBAction func buttonClicked(sender:UIButton) {
    let cell = tableView.cellForRowAtIndexPath(NSIndexPath.init(forRow: sender.tag, inSection: 0))
    cell.myLabel.text = arrayList[sender.tag]
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-07-13 11:30

In your Table View Controller

let dataSource: [String] = [ "aaa" , "bbb" , "ccc"]

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier(YourCellIdentifier, forIndexPath: indexPath) as! YourCell
    let title = dataSource[indexPath.row]
    cell.setup(withTitle: title, delegate: self)
    return cell
}

// MARK: - Your Cell Delegate
func didTapActionButton(fromCell cell: UITableViewCell) {
    if let indexPath = itemTable.indexPathForCell(cell) {
        let selectedItem = dataSource[indexPath.row]
        print(selectedItem)
    }
}

In your Table View Cell

Firstly, define a protocol:

protocol YourTableViewCellDelegate {
    func didTapActionButton(fromCell cell: UITableViewCell)
}

And then:

// MARK: - Properties
var delegate: YourTableViewCellDelegate?

// MARK: - @IBOutlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var infoButton: UIButton!

// MARK: - @IBActions
@IBAction func buttonClicked(sender: UIButton) {
    delegate?.didTapActionButton(fromCell: self)
}

// MARK: - Public Methods
func setup(withTitle title: title, delegate: YourTableViewCellDelegate?) {
    titleLabel.text = title
    self.delegate = delegate
}
查看更多
我命由我不由天
4楼-- · 2019-07-13 11:38

you need to do like

swift3

myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: #selector(yourVCName.buttonClicked(_:)), for: .touchUpInside)

get action as

 @IBAction func buttonClicked(_ sender: UIButton){

     print(self.arrayList[sender. tag])

}

Swift2

myCell.titleLable.text = self.arrayList[indexPath.row]
myCell.infoButton.tag = indexPath.row
myCell.infoButton.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)


@IBAction func buttonClicked(sender: UIButton){

     print(self.arrayList[sender. tag])

}
查看更多
登录 后发表回答