无法与表视图标题中的控件进行交互

时间:2014-08-06 21:07:23

标签: ios uitableview uisearchbar uisegmentedcontrol

我决定在我的应用中使用表格标题视图来保存搜索栏和UISegmentedControl。以下是视图控制器的viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 65, 320, 44)];
    [self.searchBar sizeToFit];
    [self.searchBar setUserInteractionEnabled:YES];
    [self setSearchController:[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self]];

    self.mainSegment = [[UISegmentedControl alloc] initWithItems:@[@"YouTube", @"iTunes"]];
    [self.mainSegment setFrame:CGRectMake(8, 109, 305, 29)];
    [self.mainSegment setSelectedIndex:0];
    [self.mainSegment addTarget:self action:@selector(searchTypeChanged:) forControlEvents:UIControlEventValueChanged];
    [self.mainSegment setUserInteractionEnabled:YES];

    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 65)];
    [headerView setBackgroundColor:[UIColor clearColor]];
    [headerView addSubview:self.searchBar];
    [headerView addSubview:self.mainSegment];
    [headerView bringSubviewToFront:self.searchBar];
    [headerView bringSubviewToFront:self.mainSegment];
    [headerView setUserInteractionEnabled:YES];

    self.tableView.tableHeaderView = headerView;
    self.tableView.userInteractionEnabled = YES;
}

这会产生一个好结果:

image

但是,我无法与搜索栏或分段控件进行交互。我尝试将userInteractionEnabled设置为YES,如上所示,但问题仍然存在。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

标题视图的高度为65磅。您在Y = 65时插入搜索栏,因此它超出了标题rect的范围。将您的搜索栏移动到Y = 0并将其分段控件移到它下面,它就可以正常工作了。

度过愉快的一天:)

答案 1 :(得分:0)

使用委托方法设置headerview.Create并返回此方法中的headerview。

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

别忘了设置表头高度。

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 

和头文件中的<UITableviewDatasource>表示该类实际上具有该表的数据源方法

A must read doc