简体   繁体   中英

Adding a UISegmentedControl under NavigationBar

I'm adding a UISegmentedControl right under the NavigationBar in a UITableViewController. This is the code.

- (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];
}

The view and the SegmentedControl appear on the screen well, but they are not clickable. The selector doesn't get executed when tapped on the SegmentControl; it doesn't even switch tabs! In fact, the stuff that is underneath the segmentView (items in the TableView) get clicked when you tap on it. I have tried but failed to understand why this is happening! Any suggestions would be helpful!

You are adding a view below the bounds of its super view. You may see the view however you cannot click it because it is out of bounds. If you set the property of the navigation bar clipsToBounds to YES you should see that the view disappears. What you need to do is add the segment controller to the table view. Here is an example:

- (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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM