A. Sola
A. Sola

Reputation: 117

How to tap buttons or images without selecting the whole cell with Swift?

I'm using a custom TableViewCell in my iOS app. I use the method tableViewDidSelectRowAtIndexPath to open a new ViewController. What I need to do is to add a button or an image somewhere in the custom cell so if I tap the button or whatever element don't open the ViewController, but execute a function without opening the cell.

Upvotes: 2

Views: 666

Answers (2)

sp309
sp309

Reputation: 150

This code may helps you

here i have used custom buttom in table and add target to that buton

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


    let cell: AnyObject = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath)

    // use your custom cell here



    //cell = UIColor.redColor()


    //cell.textLabel?!.text = String(data[indexPath.row])

    //nameTextField.text = ""

    let custom_btn : UIButton? = UIButton.init(type: .System)
    //declaring custom button

    custom_btn?.setTitle("custom button", forState: .Normal)

    custom_btn!.tag = indexPath.row

    custom_btn!.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

    cell .addSubview(custom_btn!);

    return cell as! UITableViewCell
}



func buttonClicked(sender:UIButton)
{
    if(sender.tag == 5){

       //Do something for tag
    }
    print("hello")
}

Upvotes: 1

JAY RAPARKA
JAY RAPARKA

Reputation: 1326

set [cell.button setTag:indexPath.row] in cellForRowAtIndexPath method.

and than addTarget to cell.button like

[cell.button addTarget:self action:@selector(yourAction:) forControlEvents:UIControlEventTouchUpInside]];

and than do Whatever you want to do in yourAction

with getting tag from sender.

Or you want code for that than please add your code what you had done so we can help more if you are new in iOS.

Upvotes: 1

Related Questions