简体   繁体   中英

Swift 3.0 TableView Cell Button

I have set up a button on the tableview cell and I am wondering how I can manipulate it. Namely, I am interested in changing the name title of the button and add another target (different capabilities of the button) to when the button is clicked. My thinking is that this needs to be added into the buttonClicked func, but I am not sure how to reference the specific cellForRow that was clicked. Perhaps a conditional can be used to in cellForRow that determines what the button title is? I am not too sure what the best way to go about this is.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = guestTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 

    let button : UIButton = UIButton(type:UIButtonType.custom) as UIButton

    button.frame = CGRect(origin: CGPoint(x: 200,y :60), size: CGSize(width: 100, height: 24))
    let cellHeight: CGFloat = 44.0
    button.center = CGPoint(x: view.bounds.width / (4/3), y: cellHeight / 2.0)


    button.setTitleColor(.blue, for: .normal)
    button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
    button.setTitle("Add", for: UIControlState.normal)

    cell.addSubview(button)


    return cell
}

func buttonClicked(sender : UIButton!) {
    print("Added!")


}

For Swift 3.2 and 4.0

Find " indexPath.row " and " indexPath.section "

//Add target on button in "cellForRowAt"

cell.myBtn.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)

// Add function

func btnAction(_ sender: UIButton) {

    let point = sender.convert(CGPoint.zero, to: yourTableView as UIView)
    let indexPath: IndexPath! = yourTableView.indexPathForRow(at: point)

    print("row is = \(indexPath.row) && section is = \(indexPath.section)")
}

Chnage And Add With Your Code

    button.addTarget(self, action:#selector(YourViewController.buttonClicked(_:)), for: .touchUpInside)

    button.tag = indexPath.row



func buttonClicked(sender : UIButton!) {
    print("Added!")
     let row = sender.tag;
    print(row)

}

There are two ways you can do it - the cheat's way or the proper way. The proper was is to subclass UITableViewCell, in which case you can hookup outlets in the normal way. The cheat's way is to use each element's tag property. If you set the tag of the button to (say) 1, you can use cell.viewWithTag within cellForRowAt to locate it: As in:

let button = cell.viewWithTag(1) as! UIButton

Be aware that it will search the whole hierarchy below cell , so you need to ensure you don't have multiple subviews with the same tag.

From your question, I'm guessing you want to click the button and have its title changed. The click handler should just reload the tableView row (or whole table if you're lazy like me), and cellForRowAt needs to know what title to show. This state of what to show on the button for each row must be held outside the tableView cell, since cells are reused as you scroll. This means that once the top row scrolls off the screen that same cell might be reused for the (say) 20th row. The code in cellForRowAt needs to completely reset the content of the cell in case it was already used for another row.

Adding some detail from your comment on the question, you never want to avoid reusing cells because this is a very good thing. You might be showing a table of 1,000 rows but only 10 are visible on screen. Reusing cells means iOS can create as few as 10 cells to show your entire table, rather than 1,000. Performance is faster as a result.

In Swift 4.x , you may simply have the TableView's delegate set a tag to it, like this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    // Assign tags
    cell.myButton.tag = indexPath.row

    return cell
}

Then connect your button from the Storyboard by right-click + drag to your .swift file as an @IBAction , select Type -> UIButton and click Connect .

Here's the code:

 @IBAction func myButt(_ sender: UIButton) {
    let buttTag = sender.tag // get the Tag of the clicked button in the Cell

    // write the code that will be called on click of your button 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM