グループ化されたテーブルで作業しており、tableView: viewForHeaderInSection: メソッドを使用してセクションのヘッダーをカスタマイズし、tableView: heightForHeaderInSection: を使用して高さを設定しています。
ビューを作成し、次のようにラベルを配置しました。
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// Create a custom title view.
UIView *ctv;
UILabel *titleLabel;
// Set the name.
{...} // Code not relevant
// If an iPhone.
if ([Config isPhone]) {
ctv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, 320, 36)];
}
// If an iPad
else {
ctv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 768, 75)];
titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 544, 55)];
}
// Config the label.
{...} // Code not relevant
// Center the items.
ctv.center = CGPointMake(tableView.center.x, ctv.center.y);
titleLabel.center = ctv.center;
// Add the label to the container view.
[ctv addSubview:titleLabel];
// Return the custom title view.
return ctv;
}
画面を回転させるまで、これはすべてうまく機能します。位置がずれています。これは、ビューが他の方向にあるときに中心に配置されているため、中心の計算が正しくないためであることに気付きました。解決策は、制約を追加することです。以下の制約を追加してみました:
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(ctv);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|[ctv]|"
options:0
metrics:nil
views:viewsDictionary
];
[tableView addConstraints:constraints];
しかし、以下の方法を試してみると、親ビューが関連付けられていないことがわかります。これは、技術的にビューに追加されないため、完全に理にかなっています。だから私はこのように制約を追加しようと思った:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:ctv
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:tableView
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0
];
[tableView addConstraint:constraint];
しかし、これもエラーです。tableView 変数をグローバル テーブル プロパティに切り替えようとしましたが、同じ結果が得られます。また、ビューに制約を追加する方法を見つけようとしましたが、メソッドをロードしましたが、テーブル オブジェクトからテーブルのセクション ヘッダーに戻る方法がわからなかったため、失敗しました。私が最後に考えたのは、制約でテーブルの幅を設定し、1 つをテーブル全体の中央に設定することでした。このプロセスは機能しましたが、アプリが横向きの場合、アプリの真ん中に醜いスクロールが表示されます。問題は、この制約を追加するためにロードされた後、個々のセクション ヘッダーにどこでどのようにアクセスできるかということです。私はまだObjective-Cにかなり慣れていないので、助けていただければ幸いです。
***** rdelmar の提案に基づく新しいコード ****
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *ctv = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"groupHeader"];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 544, 55)];
[titleLabel setTranslatesAutoresizingMaskIntoConstraints: NO];
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:ctv
attribute:NSLayoutAttributeCenterX
relatedBy:0
toItem:titleLabel
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0
];
[ctv addConstraints:@[constraint]];
titleLabel.text = @"string";
[ctv addSubview:titleLabel];
return ctv;
}
しかし、私が述べたように、「制約には最初のレイアウト項目が含まれている必要があります」というエラーが表示されます。