我们都知道分类中一般只能增添方法
但是如果我们想在分类中增添属性,是相当麻烦的
之前尝试也没有成功,之后查找资料发现可以实现,用到tuntime 运行时的知识
#import "ViewController+TableView.h"
#import <objc/runtime.h>
#define Set_Associated_Object(key, value) objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
#define Get_Associated_Object(key) objc_getAssociatedObject(self, key)
@implementation ViewController (TableView)
const char _tableView;
- (UITableView *)tableView {
return Get_Associated_Object(&_tableView);
}
- (void)setTableView:(UITableView *)tableView {
return Set_Associated_Object(&_tableView, tableView);
}
- (void)setUpTableView {
UITableView *tableView = [[UITableView alloc] init];
tableView.frame = self.view.bounds;
self.tableView = tableView;
// self.tableView.backgroundColor = [UIColor cyanColor];
self.view.backgroundColor = [UIColor cyanColor];
self.tableView.alpha = 0.5;
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
}
#pragma mark - DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellName = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellName];
}
cell.textLabel.text = @"test";
return cell;
// return [UITableViewCell new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 44;
}
@end

2288

被折叠的 条评论
为什么被折叠?



