2013-05-22 2 views
0

enter image description hereУвеличение пространства между заголовком и ячейки таблицы в прошивкой

Так мой UITableView имеет заголовок, который является UIImageView показано и комментарии ниже изображения. Я пытаюсь увеличить пространство между изображением и таблицей комментариев.

(Я попытался увеличения высоты заголовка, но он не работает в моем случае, потому что это приведет к более крупный UIImageView и изображение не будет покрывать вид полностью)

I экспериментировал с этим хака:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"CommentsTableCell"; 
    CommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    Comment *comment = [self.comments objectAtIndex:indexPath.row]; 
    [cell setUsername:comment.handle andText:comment.text]; 

    /* Dirty hack: 
    1. We cannot increase the height of the header because that will leave spaces in the image. 
    2. The only way we can increase the margin from the comments table to the picture is by 
    increasing the individual inset of the first and last comments cell 
    */ 
    if (indexPath.row == 0) { 
     [cell setContentInset:UIEdgeInsetsMake(COMMENTS_PADDING * 10 , 0, 0, 0)]; 
    } else if (indexPath.row == [self.comments count] - 1) { 
     [cell setContentInset:UIEdgeInsetsMake(0, 0, COMMENTS_PADDING * 10 , 0)]; 
    } 

    return cell; 
} 

и в моем CommentsCell.m:

- (void)awakeFromNib { 
    self.commentText.scrollEnabled = false; 
    self.commentText.editable = false; 
    self.commentText.contentInset = UIEdgeInsetsMake(-1 * COMMENTS_PADDING, 0, 0, 0); 
} 

- (void)setUsername:(NSString *)username andText:(NSString *)text { 
    [self.commentText setAttributedText:[CommentsCell getContentStringForUsername:username andText:text]]; 
} 

- (void)setContentInset:(UIEdgeInsets)inset { 
    self.commentText.contentInset = inset; 
} 

, но первый комментарий все еще имеет ту же самую вставку. Я проверил отладчик и awakeFromNib происходит доcellForRowAtIndexPath. Вы видите, почему мой метод не работает?

Я также открыт для других предложений.

ответ

2

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

- (UIView *) buildTableHeaderView { 

    UIImage *image = [UIImage imageNamed: @"my_image.png"]; 
    CGFloat height = image.size.height + 20; 

    UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, self.myTableView.frame.size.width, height)]; 
    [imageView setImage: image]; 

    UIView *headerView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.myTableView.bounds.size.width, height)]; 
    [headerView addSubview: imageView]; 

    return headerView; 
} 
1

Что вы можете сделать, это создать пользовательский UIView (с .xib, если хотите, для упрощения дизайна пользовательского интерфейса) с пространством внизу и вернуть его с - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section методом UITableViewDelegate, также не забудьте вернуть высоту для представления заголовка, реализуя метод - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section того же UITableViewDelegate.

Вот краткий пример:

-UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    YourCustomHeaderView *headerView = [YourCustomHeaderView instantiateView]; //static method (you can rename it) that will load the custom view from a .xib 
    //do aditional UI setup or not 
    return headerView; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { 
     return DEFAULT_HEADER_HEIGHT; //a defined value 
} 

Если у Вас есть один вид заголовка, то вы должны использовать один и тот же пользовательский вид заголовка создания/инициализации/установки, но переместить таблицу вниз в это SuperView и добавьте пользовательский заголовок вверху в любом положении, которое вам нравится.

Смежные вопросы