在UITableViewCell中修改UIView外观的正确方法是什么?

时间:2014-05-11 17:42:29

标签: ios objective-c uitableview uiview

假设您有一个自定义UITableViewCell,并且在单元格内有一个UIView,您希望在其中有一个右下角和右上半径。在哪里进行这些更改的正确位置?

我假设它不在UITableViewCell的drawRect中,因为这将是一个巨大的性能影响。 UITableViewCell中是否还有其他功能可以执行此操作?或者我应该在函数<{p>中的UITableViewController中执行此操作

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

3 个答案:

答案 0 :(得分:1)

在cellForRowAtIndexPath中实例化自定义单元格后,我会这样做:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

NSString *cellIdentifier = @"cell";
UICustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
     cell.customview.layer.cornerRadius = 5.0f;
    //add other custom stuff here as well
}

return cell;
}

答案 1 :(得分:0)

由于这个视图是由单元格拥有的,我会在单元格的init方法中进行 - 我认为最好保留任何不依赖于索引路径的视图设置或修​​改(即不是动态的)超出表视图的数据源方法。哪种init方法取决于你如何制作你的细胞。如果在故事板中创建单元格,则使用initWithCoder :,如果在xib中,则使用initWithNibName:bundle:。另一种方法是将该视图本身子类化,并在其init方法中进行修改。

答案 2 :(得分:0)

我建议使用UITableViewCell子类,并将自定义视图与自定义半径一起添加到contentView中。

这是我的简单实现。

#import "TableViewCell.h"
#import "RoundedView.h"

@implementation TableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
      RoundedView  *roundedView = [[RoundedView alloc] initWithFrame:CGRectInset(self.contentView.bounds, 2, 2)];
      [self.contentView addSubview:roundedView];
    }
    return self;
}

@end

圆形的我只需将圆角设置为所需的边缘。

#import "RoundedView.h"

@implementation RoundedView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
      self.backgroundColor = [UIColor clearColor];
    }
    return self;
}


- (void)drawRect:(CGRect)rect{

  CGContextRef context = UIGraphicsGetCurrentContext();

  UIBezierPath *bp = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomLeft cornerRadii:CGSizeMake(10, 10)];
  CGContextAddPath(context, bp.CGPath);
  CGContextClip(context);
  [[UIColor brownColor]  setFill];
  UIRectFill(rect);

}

@end

在cellForRowAtIndexPath:中,

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  TableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
  if(!cell){
    cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
  }
  return cell;
}

注意,由于视图仅在initWithStyle:reuseIdentifier:方法内添加到单元格,因此只有在分配新单元格时才会绘制视图。大多数情况下,UITableView会使单元格出列,因此只需要很少的时间。

最终结果如下所示,

enter image description here