简体   繁体   中英

How to Call a Add Target Button Function in a UITableViewCell from UITableView?

I dynamically created several buttons in my UITableViewCell class like so:

for (clientObjectId, _) in connectedObjectIds {
    self.clientNameButton = UIButton(type: UIButtonType.System) as UIButton
    self.clientNameButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail
    self.clientNameButton.frame = CGRectMake(self.leftSideSpaceForUsersAndUserLabel, clientNameButtonFrameHeight, self.nameButtonWidth, self.nameButtonHeight)
    self.clientNameButton.setTitle(self.userObjectIdsAndNames[clientObjectId], forState: UIControlState.Normal)
    self.clientNameButton.titleLabel!.font = UIFont(name: "Helvetica", size: 12.0)
    self.clientNameButton.addTarget(self, action: "asdf:", forControlEvents: UIControlEvents.TouchUpInside)
    self.nameButtons.append(self.clientNameButton)
    self.addSubview(self.clientNameButton)
}

I want to call the following function in my UITableView class:

func asdf(sender:UIButton) {
     print("Button tapped")
}

I am thinking of using a protocal to receive the asdf() function call from my UITableView class. But is there a better way?

Edit

The difference between the possible duplicates is that the addTarget occurs in the UITableView class in a UITableView delegate function. However, I do not addTarget in the delegate function but rather in my UITableViewCell. I already read that post and it did solve my problem. That is why I asked it here with another post.

Also, the other possible duplicate was my question. And I asked this question in that post but was asking two questions in one post, so I decided to post this post so that I am not asking two questions in one post.

try this code,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell Identifier";

    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.playButton.tag = indexPath.row
    cell.playButton.addTarget(self, action: Selector("buttonPressed:"), forControlEvents: .TouchUpInside)
    return cell;

}

Action:

func buttonPressed(sender:UIButton!) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! PlayViewController
        self.navigationController?.pushViewController(controller, animated: true)
    }

hope its helpful

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