【发布时间】:2013-01-30 19:57:06
【问题描述】:
我正在使用一个分组表,并且正在使用 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 变量切换到全局表属性,但它给出了相同的结果。我还试图弄清楚如何在视图中添加约束确实加载方法但它失败了,因为我无法弄清楚如何从表对象返回到表的节标题。我最后的想法是在约束中设置表格的宽度,并设置一个使整个表格居中。这个过程有效,但现在我的应用程序中间有一个丑陋的滚动条,当它处于横向时。所以问题是,在加载单个节标题以添加此约束后,我在哪里/如何访问它们?我对 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;
}
但就像我提到的,它给了我一个“约束必须包含第一个布局项”错误。
【问题讨论】:
-
是否需要在标题视图中添加约束?我不确定你知道。我认为您可以使用 CGRectZero 创建它,并将其高度设置为 heightForHeaderInSection。我很确定宽度将是表格宽度。
-
那么在没有框架的情况下启动视图和标签?我试图将 ctv 的宽度保持在我在表头中设置图像的宽度的主要原因。也许我可以尝试将约束和宽度添加到标签而不是视图中,并在没有框架的情况下启动视图(如果我能做到这一点......我将不得不查找它......对不起菜鸟)。
-
是的,您可以为标题的任何子视图设置约束(并且可能应该)。
-
嗯,那种工作。没有解决问题,但我没有得到一个完全错误的错误。我遇到了冲突约束,但我没有在节标题上设置其他约束,所以不太确定。
标签: ios objective-c uitableview constraints