在定制的tableViewCell中,要显示cell中界面的数据,就必须在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath这个方法里面将数据传到cell中,然后重写数据源的set方法,给cell里面的空间赋值。
而要在cell里面将事件的响应方法实现,则要通过代理方法,让控制器知道。然后在控制器中实现代理方法。
今天要记录的要实现这样的一个效果:在cell中有一个button,点击button可以增加一个label,计算label的宽高以及删除。
主要代码如下:`- (void)setMaterialsArray:(NSMutableArray *)materialsArray{
//将传进来的数组遍历
_materialsArray = materialsArray;
[self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
[_materialsArray enumerateObjectsUsingBlock:^(YWMaterial* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
UILabel * label = [self newPersonNameLabel];
//计算label的宽高
label.frame = CGRectMake(10 + KNameLabelWidth * (idx % 3) + KLabelGap * (idx % 3),10 + (idx/3)*(KNameLabelHeight+KcontentGap), KNameLabelWidth, KNameLabelHeight);
label.text = obj.materialName;
[self.contentView addSubview:label];
UIButton *cancelButton = [self newCancelButton];
//这个tag主要用于响应事件
cancelButton.tag = 1000 + idx;
//计算取消按钮的宽高
cancelButton.frame = CGRectMake(CGRectGetMaxX(label.frame)-8, 3 + (idx/3)*(KNameLabelHeight+KcontentGap), KCancelBtnSize, KCancelBtnSize);
[self.contentView addSubview:cancelButton];
}];
self.selectButton.frame = CGRectMake(10 + KNameLabelWidth * (_selectedContactsArray.count % 3) + KLabelGap * (_selectedContactsArray.count % 3), (_selectedContactsArray.count/3)*(KNameLabelHeight+KcontentGap) + 10, KNameLabelWidth, KNameLabelHeight);
[self.contentView addSubview:self.selectButton];
}
- (void)handleCancelSelectButtonEvent:(UIButton*)sender{
cancelButton的响应事件:
NSInteger tag = sender.tag-1000;
[self.selectedContactsArray removeObjectAtIndex:tag];
if ([self.delegate respondsToSelector:@selector(cancelButtonEvent:)]) {
[self.delegate cancelButtonEvent:tag];
}
}
`