【发布时间】:2023-04-03 14:50:01
【问题描述】:
这是我在这里的第一篇文章,所以我希望一切都正确。
我正在尝试在 Objective-C 中编写代码,允许我在表头视图中为特定部分添加 UIButton。
它应该是这样的:
我正确地看到了标题,但不幸的是 UIButton 没有出现,我不知道为什么.. 几个月前我使用了类似的代码并且它有效,但是由于另一个错误而改变了一些东西表格视图,它停止工作,不幸的是我没有原始代码了..
你知道我错在哪里或者你知道任何替代方案吗?
这是 Objective-C 中的代码(应该自动对齐标题和按钮,即使用户更改设备方向并且它应该适用于任何屏幕尺寸):
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (section == 2) {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, 0,0)];
[view setClipsToBounds:NO];
[view setPreservesSuperviewLayoutMargins:TRUE];
UILabel *textLabel = [[UILabel alloc] init];
textLabel.text = @"MY TITLE";
textLabel.textColor = [UIColor colorWithRed:0.427f green:0.427f blue:0.427f alpha:1.0f];
//[textLabel setFont:_tableViewFooterFont];
[textLabel setTextAlignment:4]; // Natural
[textLabel setTranslatesAutoresizingMaskIntoConstraints:FALSE];
[textLabel setAccessibilityTraits:UIAccessibilityTraitHeader];
[view addSubview:textLabel];
UIButton *button = [UIButton buttonWithType:1];
//[button setHidden:FALSE];
//[button.titleLabel setFont:_tableViewFooterFont];
[button.titleLabel setTextColor:[UIColor redColor]];
[button setTranslatesAutoresizingMaskIntoConstraints:FALSE];
[button setTitle:@"RESET" forState:0];
[button setContentCompressionResistancePriority:0 forAxis:UILayoutConstraintAxisHorizontal];
[button addTarget:self action:@selector(resetAction:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
NSDictionary *dictionary = NSDictionaryOfVariableBindings(textLabel, button);
NSLayoutConstraint *buttonConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"|-[textLabel]->=0-[button]-|" options:0 metrics:NULL views:dictionary];
[view addConstraints:buttonConstraint];
NSLayoutConstraint *labelConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-12-[textLabel]-6-|" options:0 metrics:NULL views:dictionary];
[view addConstraints:labelConstraint];
NSLayoutConstraint *viewConstraint = [NSLayoutConstraint constraintWithItem:button attribute:10 relatedBy:0 toItem:textLabel attribute:10 multiplier:1.0 constant:0];
[view addConstraint:viewConstraint];
return view;
}
return NULL;
}
【问题讨论】:
标签: ios objective-c uitableview