2013-06-26 3 views
1

Я добавляю границу к UITableViewCell. Ниже приведен код:Как решить проблему перекрытия границы в UITableViewCell?

Try-1:

cell.layer.borderWidth = 1; 
cell.layer.borderColor = [UIColor redColor].CGColor; 

Try-2:

cell.contentView.layer.borderWidth = 1; 
cell.contentView.layer.borderColor = [UIColor redColor].CGColor; 

Я попробовал оба эти пути, вот выход. enter image description here

Как вы можете найти на изображении, граница перекрывается между двумя ячейками, поскольку этот цвет становится темнее, чем пограничные ячейки.

Почему я не добавил границу стола?

  • Проблема в том, я использую три Diff пользовательских ячеек в одной таблице, в соответствии с данными, особенно ячейка загружается
  • Поэтому я не могу добавить цвет границы для всей UITableView или не в состоянии сделать границы ячеек в cellforrowatindexpath. Потому что в этом методе только я проверяю, какой тип данных он есть, и соответственно пользовательская ячейка была загружена.

Вот мой cellForRowAtIndexPath:

- (UITableViewCell*) getTableViewCellForTraining:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath withTrainingInfo:(TrainingInfoiOS*)trainingInfo 
{ 
    BeLearnPlatform& ptr = BeLearnPlatform::GetLearnPlatform(); 

    static NSString *CustomCellIdentifier = @"CustomCell"; 
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier forIndexPath:indexPath]; 
    cell.courseNameLabel.text = trainingInfo.courseName; 
    cell.courseStartButton.sectionID = indexPath.section; 
    cell.courseStartButton.rowID = indexPath.row; 
    cell.tag=0; 
... 
} 
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     UITableViewCell* cell = nil; 
     NSString* dictionaryKey = [self createKeyWithSection:indexPath.section andRow:indexPath.row]; 
     NSObject* dataObject = [tableViewMappig objectForKey:dictionaryKey]; 

     if([dataObject isKindOfClass:[MasterCourse class]]) 
      { 
      UITableViewCell* cell = [self getTableViewCellForTraining:tableView cellForRowAtIndexPath:indexPath withTrainingInfo:(MasterCourse*)dataObject]; 
      return cell; 
      } 
     else if([dataObject isKindOfClass:[ParentCourse class]]) 
      { 
      UITableViewCell* cell = [self getTableViewCellForParentCourse:tableView cellForRowAtIndexPath:indexPath withTrainingInfo:(ParentCourse*)dataObject]; 
      return cell; 
      } 

Пожалуйста, предложите мне решение для этого.

+0

Добавить разделитель в tableViewCell и добавить пограничный слой в таблицуView – Dilip

+0

Я не могу этого сделать. Есть несколько ячеек, которые имеют разную компоновку, чем это. Это пограничные ячейки. Таким образом, я не могу добавить разделительную линию ко всему представлению таблицы. – Mrunal

ответ

3

Хорошо, это идея.

Вы можете сделать это так, добавьте этот код в cellForRowAtIndexPath метод, в котором вы создаете ячейку.

Если вы хотите применить порядок в ячейке с индексом 1,2 и 3, чем ...

if (indexPath.row == 1||indexPath.row == 2) 
     { 

    //Display vertical line on top of the cell 
      UIView* vLineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)]; 
      vLineview.backgroundColor = [UIColor redColor]; 
      [cell addSubview:vLineview]; 
    //Display horizontal line on left of the cell 
//44 is default cell size you can change it according to your cell value 
    UIView* hLineview1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 44)]; 
      hLineview1.backgroundColor = [UIColor redColor]; 
      [cell addSubview:hLineview1]; 

    //Display horizontal line on right of the cell 
    UIView* hLineview2 = [[UIView alloc] initWithFrame:CGRectMake(319, 0, 1, 44)]; 
      hLineview2.backgroundColor = [UIColor redColor]; 
      [cell addSubview:hLineview2]; 
    } 
//Now we give last cell to display vertical line on bottom 

if (indexPath.row == 3) 
      { 

     //Display vertical line on top of the cell 
       UIView* vLineview = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 320, 1)]; 
       vLineview.backgroundColor = [UIColor redColor]; 
       [cell addSubview:vLineview]; 

     //Display horizontal line on left of the cell 
    //44 is default cell size you can change it according to your cell value 
     UIView* hLineview1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 44)]; 
       hLineview1.backgroundColor = [UIColor redColor]; 
       [cell addSubview:hLineview1]; 

     //Display horizontal line on right of the cell 
     UIView* hLineview2 = [[UIView alloc] initWithFrame:CGRectMake(319, 0, 1, 44)]; 
       hLineview2.backgroundColor = [UIColor redColor]; 
       [cell addSubview:hLineview2]; 

     //i have added this now 
     //Display vertical line on Bottom of the cell 
       UIView* vLineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)]; 
       vLineview.backgroundColor = [UIColor redColor]; 
       [cell addSubview:vLineview]; 

     } 

Это добавит границу в ячейке, которая находится на 1,2 и 3-й позиции. Изменить значение вида в соответствии с вашими потребностями. не устанавливайте представление внизу, в противном случае возникает такая же проблема.

+0

немного опечатка ошибка проверка сейчас ... – Dilip

+0

. Извините, что ранее не сообщал об этом. Ваше решение идеально подходит, если я уже знаю данные. Но здесь во время выполнения я проверяю, какие данные поступают (потому что он проходит через webservice). Поэтому я не могу получить, какие данные будут в следующей ячейке. – Mrunal

+0

Забудьте о перекрывающейся границе. Скажите мне, как вы различаете, какой tableCiewCell получит границу, а какой нет ... bcoz на вашем скриншоте, что вы добавляете некоторую логику, чтобы отличить ячейку? – Dilip

0
@implementation BaseTableViewCell 


- (void)awakeFromNib { 
    [super awakeFromNib]; 
    // Initialization code 
    UIView *myBackView = [[UIView alloc] initWithFrame:self.frame]; 
    self.backgroundColor = [UIColor clearColor]; 
    myBackView.backgroundColor = [UIColor clearColor]; 

    self.backgroundView = myBackView; 
    self.backgroundView.layer.borderWidth = 2.0; 
    self.backgroundView.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor; 

    self.borderTop = [CALayer layer]; self.borderBottom = [CALayer layer]; 
    self.borderTop.borderColor = self.tintColor.CGColor; self.borderBottom.borderColor = self.tintColor.CGColor; 
    self.borderTop.frame = CGRectMake(0, 0, self.frame.size.width, 2); 
    self.borderTop.frame = CGRectMake(0, self.bounds.size.height, self.frame.size.width, 2); 
    self.borderTop.borderWidth = 2.0; self.borderBottom.borderWidth = 2.0; 
    [self.contentView.layer addSublayer:self.borderTop]; 
    [self.contentView.layer addSublayer:self.borderBottom]; 
    self.borderTop.hidden = YES; self.borderBottom.hidden = YES; 
    self.clipsToBounds = NO; 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
    // set selection color 
    UIView *myBackView = [[UIView alloc] initWithFrame:self.frame]; 
    self.selectedBackgroundView = myBackView; 
    self.borderTop.hidden = selected ? NO : YES; 
    self.borderBottom.hidden = selected ? NO : YES; 
    self.clipsToBounds = selected ? NO : YES; 

    myBackView.backgroundColor = [UIColor clearColor]; 
    myBackView.layer.borderColor = selected ? self.tintColor.CGColor : [UIColor groupTableViewBackgroundColor].CGColor; 
    myBackView.layer.borderWidth = 2.0; 
} 

-(void)layoutSubviews { 
    [super layoutSubviews]; 

    CGRect r; 
    UIView *defaultAccessoryView = self.subviews.lastObject; 
    r = defaultAccessoryView.frame; 
    r.origin.x = self.bounds.size.width - 50; 
    r.origin.y = - self.bounds.size.height/2 + 50; 
    defaultAccessoryView.frame = r; 

    CGRect frameBack = self.bounds; 
    frameBack.size.height += 2; 
    self.backgroundView.frame = frameBack; 
    self.selectedBackgroundView.frame = frameBack; 
} 

@end