相信在日常的開發(fā)中,應產品與UI的要求,會自定義個漂亮的Cell,cell上面的控件五顏六色,看著讓人賞心悅目??!但是,悲催的是在點擊cell的時候,所有控件的背景顏色都消失,整個cell變的灰蒙蒙的,心中頓時一群草泥馬奔過!
今天,記錄一下這個問題的幾種解決方法,也為了以后方便自己查閱。
效果:
- 點擊前:

效果圖1
- 點擊時:

效果圖2
原因:
當點擊UITableViewCell時,會使用到cell的selectionStyle屬性, 屬性的默認值是UITableViewCellSelectionStyleBlue,點擊時會將cell上子控件的背景顏色設置為透明,所以就消失了。
我們可以將selectionStyle屬性值改為cell.selectionStyle = UITableViewCellSelectionStyleNone,但是這樣點擊cell就沒有任何效果,不能滿足大部分開發(fā)者的需求。
UIImageView:
解決方法:
將顏色轉換為UIImage,然后imageView.image = image。問題就解決了,其他控件如果可以設置UIImage也可以用這個方法,例如UIButton等。
UIColor轉UIImage的方法:
//color轉image
- (UIImage *) createImageWithColor: (UIColor *) color {
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
其他方法:
對于那些不方便設置UIImage,或只能設置背景顏色的控件來說,就需要另外一種方法了。在繼承UITableViewCell的子類.m文件中,實現父類的cell按中的兩個方法,在方法中設置控件的顯示顏色。
//這個方法在Cell被選中或者被取消選中時調用
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
self.label.backgroundColor = [UIColor colorWithRed:69/255.0f green:144/255.0f blue:228/255.0f alpha:1];
self.imageView.backgroundColor = [UIColor colorWithRed:69/255.0f green:19/255.0f blue:227/255.0f alpha:1];
}
//這個方法在用戶按住Cell時被調用
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
[super setHighlighted:highlighted animated:animated];
self.label.backgroundColor = [UIColor colorWithRed:69/255.0f green:144/255.0f blue:228/255.0f alpha:1];
self.imageView.backgroundColor = [UIColor colorWithRed:69/255.0f green:19/255.0f blue:227/255.0f alpha:1];
}
實踐證明,UIImageView最好還是設置其image,在上面的兩個方法中設置控制背景顏色無效。