Skip to content

Instantly share code, notes, and snippets.

@joslinm
Last active December 15, 2015 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joslinm/5341352 to your computer and use it in GitHub Desktop.
Save joslinm/5341352 to your computer and use it in GitHub Desktop.
view tagging to get user's property
//
// BFViewController.m
// ObjcRuntimeExample
//
// Created by Mark Joslin on 3/26/13.
// Copyright (c) 2013 BitFountain. All rights reserved.
//
#import <objc/runtime.h>
#import "BFTableViewControler.h"
// Example user object
@interface User : NSObject
@property int id;
@end
@implementation User
@end
@interface BFTableViewControler ()
@end
@implementation BFTableViewControler
{
NSArray *_users;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Init our fake users
User *user = [[User alloc] init];
user.id = 1;
User *user1 = [[User alloc] init];
user1.id = 2;
User *user2 = [[User alloc] init];
user2.id = 3;
_users = @[user, user1, user2];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _users.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell with a tap gesture recognizer on the cell's text label
User *user = _users[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"User %d", user.id];
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:20.0f];
cell.textLabel.backgroundColor = [UIColor colorWithWhite:0.8f alpha:0.5f];
// Use tags to hold onto the indexPath row
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSelectCellTextLabel:)];
tapGestureRecognizer.tag = indexPath.row;
[cell addGestureRecognizer:tapGestureRecognizer];
return cell;
}
- (void)didSelectCellTextLabel:(UITapGestureRecognizer *)tapGestureRecognizer
{
// get the cell
UITableViewCell *cell = tapGestureRecognizer.view.superview;
User *user = _users[cell.tag]
cell.textLabel.text = [NSString stringWithFormat:@"%d user", user.id];
assert(user.id > 0);
assert(cell != nil);
NSLog(@"hooray, we've passed metadata inside of our callback object");
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment