Как программно установить ограничения Section-Header.xib в UITableView, используя Objective-C - PullRequest
0 голосов
/ 28 мая 2018

Я хочу установить ограничения ширины программно, используя Objective-C.

Приведенный ниже код работает нормально, когда я создаю свое приложение, используя Xcode 7.2.

  [secHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_sectionHeaderView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sectionHeaderView)]];

    [secHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_sectionHeaderView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sectionHeaderView)]];

Теперь, когда я запускаю свое приложение, используя Xcode 9.3, мои secHeaderView отсутствуют.Это из-за ограничений, которые упомянуты выше.

Если я закомментирую вышеупомянутые ограничения, то я смогу увидеть мой secHeader View, но ширина не установлена ​​должным образом.Он показывает 70% ширины UIScreen.

Так выглядит мой secHeaderView, но ширина не установлена ​​должным образом ...

enter image description here

Вот мой фактический код:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    _sectionHeaderView = [[NSBundle mainBundle] loadNibNamed:@"BasicProdInfoSectionHeaderView" owner:self options:nil].firstObject;
    SectionHeader *currentHeader = [self.titleStringArray objectAtIndex:section];

    [_sectionHeaderView setTitleWithText:currentHeader.titleLabel];
    _sectionHeaderView.expandableButton.tag = section;

    [_sectionHeaderView.expandableButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIView *secHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[[UIScreen mainScreen] bounds].size.width , 50)];
    _sectionHeaderView.translatesAutoresizingMaskIntoConstraints = NO;

    [secHeaderView addSubview:_sectionHeaderView];
    [secHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_sectionHeaderView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sectionHeaderView)]];
    [secHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_sectionHeaderView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sectionHeaderView)]];

    if (section != 3) {
        secHeaderView.layer.shadowOffset = CGSizeMake(0, 1);
        secHeaderView.layer.shadowRadius = 1;
        [secHeaderView.layer setShadowColor:[UIColor blackColor].CGColor];
        secHeaderView.layer.shadowOpacity = 0.25;
    }

    return secHeaderView;
}

Ответы [ 4 ]

0 голосов
/ 07 июня 2018

Согласно документу Apple для tableView:viewForHeaderInSection: метода

Этот метод работает правильно, только если также реализован tableView: heightForHeaderInSection:.

Так что я думаю, что проблема в том, что вы не реализовали метод tableView:heightForHeaderInSection: в своем классе.

Другая проблема заключается в том, что вам не нужно указывать secHeaderView размер внутри tableView:viewForHeaderInSection:, потому что

  • Заголовок раздела всегда будет иметь одинаковую ширину с tableView по умолчанию.
  • Правильный способ изменить высоту раздела tableView - использовать метод UITableViewDelegate tableView:heightForHeaderInSection:.

На самом деле я создал новый проект и попробовал ваш код.Работает как положено.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  _sectionHeaderView = [[NSBundle mainBundle] loadNibNamed:@"BasicProdInfoSectionHeaderView" owner:self options:nil].firstObject;
  SectionHeader *currentHeader = [self.titleStringArray objectAtIndex:section];

  [_sectionHeaderView setTitleWithText:currentHeader.titleLabel];
  _sectionHeaderView.expandableButton.tag = section;

  [_sectionHeaderView.expandableButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
  UIView *secHeaderView = [[UIView alloc] initWithFrame:_sectionHeaderView.frame];
  _sectionHeaderView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

  [secHeaderView addSubview:_sectionHeaderView];

  if (section != 3) {
    secHeaderView.layer.shadowOffset = CGSizeMake(0, 1);
    secHeaderView.layer.shadowRadius = 1;
    [secHeaderView.layer setShadowColor:[UIColor blackColor].CGColor];
    secHeaderView.layer.shadowOpacity = 0.25;
  }

  return secHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  return 50;
}
0 голосов
/ 28 мая 2018

Я бы предложил это.Вам не нужно устанавливать рамку для раздела superview.Поскольку табличное представление устанавливает его автоматическое расположение автоматически.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    _sectionHeaderView = [[NSBundle mainBundle] loadNibNamed:@"BasicProdInfoSectionHeaderView" owner:self options:nil].firstObject;
    SectionHeader *currentHeader = [self.titleStringArray objectAtIndex:section];

    [_sectionHeaderView setTitleWithText:currentHeader.titleLabel];
    _sectionHeaderView.expandableButton.tag = section;

    [_sectionHeaderView.expandableButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIView *secHeaderView = [[UIView alloc] init];
    _sectionHeaderView.translatesAutoresizingMaskIntoConstraints = NO;

    [secHeaderView addSubview:_sectionHeaderView];
    [_sectionHeaderView.bottomAnchor constraintEqualToAnchor:secHeaderView.bottomAnchor constant:0]
    [_sectionHeaderView.leadingAnchor constraintEqualToAnchor:secHeaderView.leadingAnchor constant:0]
    [_sectionHeaderView.trailingAnchor constraintEqualToAnchor:secHeaderView.trailingAnchor constant:0]


    if (section != 3) {
        secHeaderView.layer.shadowOffset = CGSizeMake(0, 1);
        secHeaderView.layer.shadowRadius = 1;
        [secHeaderView.layer setShadowColor:[UIColor blackColor].CGColor];
        secHeaderView.layer.shadowOpacity = 0.25;
    }
    [secHeaderView layoutIfNeeded]

    return secHeaderView;
}
0 голосов
/ 29 мая 2018

Замените эти две строки

[secHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_sectionHeaderView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sectionHeaderView)]];
    [secHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_sectionHeaderView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sectionHeaderView)]];

на

[secHeaderView
     addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_sectionHeaderView
    ]|" options:0 metrics:nil views:@{@"_sectionHeaderView
    ":_sectionHeaderView
    }]];

    [secHeaderView
     addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_sectionHeaderView
    ]|" options:0 metrics:nil views:@{@"_sectionHeaderView
    ":_sectionHeaderView
    }]];
0 голосов
/ 28 мая 2018

Использовать ниже ограничений У меня есть изменения ниже ограничений

// center sectionHeaderView horizontally in secHeaderView
[secHeaderView addConstraint:[NSLayoutConstraint constraintWithItem:sectionHeaderView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:secHeaderView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];

// center sectionHeaderView vertically in secHeaderView
[secHeaderView addConstraint:[NSLayoutConstraint constraintWithItem:sectionHeaderView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:secHeaderView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]];

// width constraint
[secHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[sectionHeaderView(==0)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(sectionHeaderView)]];

// height constraint
[secHeaderView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[sectionHeaderView(==0)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(sectionHeaderView)]];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...