2010-05-17 216 views

回答

7

你可以做到這一點通過viewDidLoad中方法的視圖控制器:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    UIBarButtonItem* infoButton = [[UIBarButtonItem alloc] initWithTitle:@"Info" 
                    style:UIBarButtonItemStylePlain 
                    target:self 
                    action:@selector(infoButtonSelected:)]; 
    self.navigationItem.rightBarButtonItem = infoButton; 
    [infoButton release]; 
} 

在當按鈕被點擊約的例子,你也應該有方法:

- (void)infoButtonSelected:(id)sender { 
     NSLog(@"button tapped"); 
     // whatever needs to happen when button is tapped 
} 
+0

你給的例子是完美的。非常感謝! – dubbeat 2010-05-17 12:11:43

0

將其添加到當前控制器的navigationItem中。它具有leftBarButtonItem和rightBarButtonItem屬性。

0
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems: 
    [NSArray arrayWithObjects: 
     [UIImage imageNamed:@"change frame btn.png"], 
     [UIImage imageNamed:@"im.jpeg"], 
     //[UIImage imageNamed:@"im.jpeg"], 
     nil]]; 

    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged]; 
    segmentedControl.frame = CGRectMake(0, 0, 150, 30); 
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
    segmentedControl.momentary = YES; 

    UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl]; 
    [segmentedControl release]; 

    self.navigationItem.rightBarButtonItem = segmentBarItem; 
    [segmentBarItem release]; 
} 

- (void)segmentAction:(id)sender{ 

    if([sender selectedSegmentIndex] == 0) 
    { 
    } 
    if([sender selectedSegmentIndex] == 1) 
    { 
    } 
+0

嗨,你可以重新格式化你的代碼,以便我可以正確閱讀嗎? :) – dubbeat 2010-05-17 12:26:59

0

navigationBar只是一個UIView,所以你可以創建一個UIButton和addSubview。 它必須是viewDidAppear不是viewdidLoad。

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 


    // this must be AFTER The animation - otherwise it wont appear in the right spot 
    int xpos=self.navigationController.navigationBar.frame.size.width/2+60; 
    _toggleOnDeviceButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [_toggleOnDeviceButton addTarget:self action:@selector(toggleButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    [_toggleOnDeviceButton setFrame:CGRectMake(xpos,2,40,40)]; 
    [_toggleOnDeviceButton setImage:[UIImage imageNamed:@"blank_button.png"] forState:UIControlStateNormal]; 
    [_toggleOnDeviceButton setTitle:@"Go" forState:UIControlStateNormal]; 
    _toggleOnDeviceButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin; 
    [self.navigationController.navigationBar addSubview:_toggleOnDeviceButton]; 

} 
相關問題