功能:点击展开,按钮变色,再次点击收缩,按钮恢复;
问题:圆我是用UIViewLayer实现,定义了一个属性choosed
- (void)layerAction {
self.backgroundColor = [UIColor clearColor];
[self.roundView.layer setCornerRadius:self.roundView.frame.size.width/2.0];
[self.roundView.layer setBorderColor:[UIColor whiteColor].CGColor];
[self.roundView.layer setBorderWidth:1.0f];
}
- (void)setChoosed:(BOOL)choosed {
[self layerAction];
_choosed = choosed;
if (choosed) {
self.roundView.backgroundColor = [UIColor whiteColor];
self.titleLabel.textColor =[ UIColor redColor];
} else {
self.roundView.backgroundColor = [UIColor clearColor];
self.titleLabel.textColor = [UIColor whiteColor];
}
}
然后在tableview中这样写的:
RoundButton *roundCell = (RoundButton *)[tableView dequeueReusableCellWithIdentifier:roundBtnCell forIndexPath:indexPath];
[roundCell setChoosed:NO];
NSArray *data = self.dataDict[content];
NSString *sTitle = [data[indexPath.row] valueForKey:content];
roundCell.titleLabel.text = sTitle;
return roundCell;
结果因为重用机制,每次重用时Cell都会设置Choosed,导致展开后又可以再次展开
解决: 显示找到cell初始化方法 initWithCoder (话说storyboard下定制的cell原型 初始化不是进入-initWithStyle: reuseIdentifier:方法了 ,我还试了许久,以为就要成功了,其实不然,我再初始化中写:
self.choosed = NO;
但是其实这个时候Cell并没有出来,等到真正出来时,就没有实现我的切圆等操作,最终通过逻辑发现这样写最合适,各位看官见笑了。(其实只是加了个if)
RoundButton *roundCell = (RoundButton *)[tableView dequeueReusableCellWithIdentifier:roundBtnCell forIndexPath:indexPath];
if (roundCell.choosed != YES) {
[roundCell setChoosed:NO];
}
NSArray *data = self.dataDict[content];
NSString *sTitle = [data[indexPath.row] valueForKey:content];
roundCell.titleLabel.text = sTitle;
return roundCell;
最终发现还是不行,定义了一个数组保存展开的状态,demo: GitHub