在导航栏下添加分段控件

时间:2014-02-27 16:15:00

标签: ios uinavigationbar uitableview

我在UITableViewController的NavigationBar下面添加了一个UISegmentedControl。这是代码。

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationBar = self.navigationController.navigationBar;
    UIView *segmentView=[[UIView alloc] initWithFrame:CGRectMake(0, self.navigationBar.frame.size.height, self.navigationBar.frame.size.width, 50)];
    [segmentView setBackgroundColor:[UIColor whiteColor]];
    segmentView.alpha = 0.95;
    self.tabSegmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Favourites", @"All", nil]];
    self.tabSegmentedControl.frame = CGRectMake(20, 10, self.navigationBar.frame.size.width - 40, 30);
    [self.tabSegmentedControl addTarget:self action:@selector(tabChanged:) forControlEvents:UIControlEventValueChanged];
    [segmentView addSubview:self.tabSegmentedControl];
    [self.navigationBar addSubview:segmentView];
    [self.tabSegmentedControl setSelectedSegmentIndex:1];
}

视图和SegmentedControl很好地出现在屏幕上,但它们不可点击。点击SegmentControl时,选择器不会被执行;它甚至没有切换标签!实际上,点击它时,segmentView(TableView中的项目)下面的内容会被点击。我试过但却不明白为什么会这样!任何建议都会有所帮助!

1 个答案:

答案 0 :(得分:1)

您正在其超级视图的边界下添加视图。您可能会看到视图,但无法单击它,因为它超出范围。如果您将导航栏clipsToBounds的属性设置为YES,则会看到视图消失。您需要做的是将段控制器添加到表视图中。这是一个例子:

- (void)viewDidLoad
{
    [super viewDidLoad];
    ...
    [self.view addSubview: self.segmentView]; // need to keep a pointer to segmentView
    self.tableView.contentInset = UIEdgeInset(self.segmentView.frame.size.height, 0,0,0);
}

-(void) scrollViewDidScroll:(UIScrollView*) scrollView{
    CGRect rect = self.segmentView.frame;
    rect.origin = self.tableView.contentOffset;
    self.segmentView.frame = rect;
}