iOS self.navigationController.toolbar位置到顶部不会改变

时间:2014-10-15 12:29:20

标签: ios objective-c

我正在尝试将self.navigationController.toolbar位置更改为顶部而不是底部。

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIToolbarDelegate, UIBarPositioningDelegate>

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

// View did load
- (void)viewDidLoad
{
    // Superclass view did load method call
    [super viewDidLoad];

    // UIToolbarDelegate
    self.navigationController.toolbar.delegate = self;
}

- (void)viewDidLayoutSubviews
{
    self.navigationController.toolbarHidden = NO;
    self.navigationController.toolbar.frame = CGRectMake(self.navigationController.toolbar.frame.origin.x, 64.0f, self.navigationController.toolbar.frame.size.width, self.navigationController.toolbar.frame.size.height);

    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"First", @"Second"]];
    segmentedControl.frame = CGRectMake(50.0f, 10.0f, 220.0f, 24.0f);
    segmentedControl.selectedSegmentIndex = 1;
    [self.navigationController.toolbar addSubview:segmentedControl];
}

- (UIBarPosition)positionForBar:(id <UIBarPositioning>)bar
{
    return UIBarPositionTopAttached;
}

@end

位置首先发生变化,但后来又回到了底部。拜托,帮助我!

2 个答案:

答案 0 :(得分:0)

首先确保调用工具栏委托方法positionForBar:。如果没有,那么您的工具栏委托未正确设置,您必须在标题类中定义UIToolbarDelegate协议。

@interface ExampleViewController : UIViewController <UIToolbarDelegate>
...

@end

然后设置委托并更改工具栏的框架。但是,对于方向,您可能需要重新考虑工具栏的框架。

    @implementation ExampleViewController

         - (void)viewDidLoad {

             [super viewDidLoad];

             // set the toolbar delegate
             self.navigationController.toolbar.delegate = self;
             self.navigationController.toolbarHidden = NO;

             // create a toolbar child items
             UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"First", @"Second"]];
             segmentedControl.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.with, 24.0f);
             segmentedControl.selectedSegmentIndex = 1;
             [self.navigationController.toolbar addSubview:segmentedControl];

             // set the frames
             CGRect toolbarFrame = self.navigationController.toolbar.frame;
             toolbarFrame.origin.y = self.navigationController.frame.size.height;
             self.navigationController.toolbar.frame = toolbarFrame;
          }

         // pragma mark - UIToolbarDelegate
         - (UIBarPosition)positionForBar:(id <UIBarPositioning>)bar
         {
             return UIBarPositionTopAttached;
         }

   @end

答案 1 :(得分:-1)

在viewDidLoad方法中,添加:

self.navigationController.toolbar.delegate = self;