简体   繁体   English

如何为UITableView单元格设置复合背景色?

[英]How to set a composite background color for UITableView cells?

I want to divide the UITableViewCell horizontally into two. 我想将UITableViewCell水平分为两个。

Set the bottom half color to blue and top half color to light blue. 将底部的一半颜色设置为蓝色,将顶部的一半颜色设置为浅蓝色。

Also the colors need to be reversed when the cell is selected. 选择单元格时,颜色也需要反转。

I trying to implement using CALayer . 我试图使用CALayer实现。 But not much successful. 但是成功并不多。

As table contain lots of data use of image will hamper performance and use lot of memory. 由于表中包含大量数据,因此使用图像会影响性能并占用大量内存。

How do I do this? 我该怎么做呢?

为什么不使用在后台排序的两个UIView,并为每个UIView分配不同的背景颜色?

Create two UIView objects and set its background color to the ones that you want. 创建两个UIView对象,并将其背景色设置为所需的背景色。 Using these two view, create the background views for selected and normal state of the cell. 使用这两个视图,为单元格的选定状态和正常状态创建背景视图。 You do this by setting the frames of the views according to the cell's frame. 为此,您可以根据单元格的框架设置视图的框架。 Then, you need to set two properties for the UITableViewCell in cellForRowAtIndexPath: . 然后,您需要在cellForRowAtIndexPath:UITableViewCell设置两个属性cellForRowAtIndexPath:

@property(nonatomic, retain) UIView *backgroundView
@property(nonatomic, retain) UIView *selectedBackgroundView

You should be able to use the background view property of the cell 您应该能够使用单元格的背景视图属性

UITableViewCell *cell = // ... code to create table view cell

UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0,0,cell.contentView.frame.size.width, cell.contentView.frame.size.height/2);

UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0,0,cell.contentView.frame.size.width, cell.contentView.frame.size.height/2);

UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0,0,cell.contentView.frame.size.height, cell.contentView.frame.size.width);

[backgroundView addSubview:topView];
[backgroundView addSubview:bottomView];

cell.backgroundView = backgroundView;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM