Reputation: 612
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.
Upvotes: 1
Views: 2352
Reputation: 3245
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
Upvotes: 1