【问题标题】:customize UITableView Header Section at run time在运行时自定义 UITableView Header Section
【发布时间】:2015-05-30 10:57:48
【问题描述】:

我已经使用下面的代码设置了标题背景,但是当我单击添加为标题上的子视图的按钮时,我想在运行时再次将标题的颜色更改回来。 请给我代码,提前谢谢:)

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _tableView.bounds.size.width, 50)];
 header.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"homeCellHeaderBackGround.png"]];

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 30)];
    label.text = _array[section][@"name"];
    label.textColor = [UIColor whiteColor];


    [header addSubview:label];


    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(230, 10, 70, 35)];
    [button addTarget:self action:@selector(onExpandButton:) forControlEvents:UIControlEventTouchUpInside];
    //[button setTitle:@"Expand" forState:UIControlStateNormal];
    [button setTag:section];

    [header addSubview:button];

    return header;
}

【问题讨论】:

标签: ios objective-c iphone uitableview


【解决方案1】:

您可以通过以下方式在运行时修改它:

第一:

您可以声明一个全局变量/属性,例如:

@property (nonatomic) UIView *tableHeader;

并设置在-(void)viewDidLoad下

喜欢

self.tableView.tableHeaderView = self.tableHeader;

或使用 delagate:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   return self.tableHeader;
}

并在任何你喜欢的地方修改它,但不要忘记重新加载你的表格节标题,[tableView reloadSections:NSIndexSet withRowAnimation:UITableViewRowAnimation]; 可能会这样做。

但是

在您的情况下,您可以检索/获取委托内部制作的 tableHeader:

-(UIView *)tableView:tableView viewForHeaderInSection:section

通过

UIView *tableHeaderView = [self tableView:yourTableView viewForHeaderInSection:yourSection];

然后修改tableHeaderView..

或简单地通过以下方式重新分配 tableHeader:

yourTableView.tableHeaderView = tableHeaderView;

你单独使用header,因为我可以看到它是一个全局变量.. 直接更改/更新它:

header.backgroundColor = [UIColor yourNewColor];

希望我对你有所帮助.. 编码愉快,干杯..

【讨论】:

  • 所有这些信息真的很有帮助,也许我可以让它在其他场景中有用,但这次 kslcam 的回答完美无缺。但我仍然想感谢您提供的详细信息,谢谢:)
【解决方案2】:

您可以通过以下代码更改节标题的背景颜色:

- (IBAction)onExpandButton:(id)sender {
   UIView *header = ((UIButton *)sender).superView;
   header.backgroundColor = <Whatever UIColor you like>;
   ...
}

【讨论】:

  • 这就是我想要的:)
【解决方案3】:
-(IBAction)onExpandButton:(UIButton *)sender { UIView *tmpView = [self.YourTableViewName headerViewForSection:sender.tag]; tmpView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"homeCellHeaderBackGround.png"]]; }

-您从表视图标题中获得了部分方法的视图。在您可以将图像视图设置为视图之后。

【讨论】:

  • 对不起,它不工作可能是发件人是一个按钮,我认为它没有连接到它的超级视图,但使用 superView.sender 在相同的逻辑下工作正常。请参阅 aboce kslcam 答案,该答案根据我的要求完美运行:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
相关资源
最近更新 更多