使用“完成”按钮替换导航控制器上的右UIBarButtonItem

时间:2013-09-23 07:59:33

标签: iphone ios objective-c

我看了很多文章来帮助我,但却找不到答案......

我想在键盘处于活动状态时使用“完成”按钮替换右键控制按钮,然后在编辑完成后将其替换回来...

我已经有一个右键控制按钮,它是一个分段控件,在视图加载时设置。我不确定是否可以在创建条形按钮后切换它?

以下是一些屏幕截图......

Would like to change the Prev / Next Button to a done button when keyboard appears

当键盘出现时,想要将上一个/下一个按钮更改为完成按钮

Screen with Keyboard

以下是显示键盘时触发的代码...代码执行但按钮未显示...

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
// Replace the Right Navigation Button with done button

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                            target:self
                                                                            action:@selector(doneEditing)];
self.navigationItem.rightBarButtonItem = doneButton;

// Slide up the view

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];

CGRect rect = self.view.frame;

// Move the view .... Note need to calculate this based on the size of the keyboard !!

rect.origin.y -= 120.0f;
rect.size.height += 120.f;

self.view.frame = rect;

// Resize the text view .... Note need to calculate this based on screen size !!

CGSize frameSize = self.reviewTextView.frame.size;
CGPoint framePos = self.reviewTextView.frame.origin;
[self.reviewTextView setFrame:CGRectMake(framePos.x, framePos.y, frameSize.width, 200.0f)];

[UIView commitAnimations];

return YES;
}

以下是用于在加载视图时设置上一个/下一个按钮的代码段

    //set up the segmented control and add it to the nav bar rightBartButtonItem

UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"\U000025C0\U0000FE0E Prev", @"Next \U000025B6\U0000FE0E", nil]];
UIBarButtonItem * segmentControlButton = [[UIBarButtonItem alloc] initWithCustomView:segmentControl];
[segmentControl setBackgroundColor:[UIColor clearColor]];
segmentControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentControl.frame = CGRectMake(0, 0, 120, 30);
[segmentControl setMomentary:YES];
[segmentControl addTarget:self
                   action:@selector(onSegmentChanged:)
         forControlEvents:UIControlEventValueChanged];
self.navigationItem.rightBarButtonItem = segmentControlButton;

3 个答案:

答案 0 :(得分:1)

有时您需要提示系统重新绘制带有更改的栏,尝试调用[self.navigationController.navigationBar setNeedsDisplay]

答案 1 :(得分:0)

试试这个,

if(keyboardIsActive){
UIBarButtonItem *menuButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"Done"
                                   style:UIBarButtonItemStyleBordered
                                   target:self.revealViewController
                                   action:@selector(revealToggle:)];

    destinationViewController.navigationItem.leftBarButtonItem = menuButton;}

答案 2 :(得分:0)

我很抱歉,但这是我的编码错误...

来自用户MICANTOX的支持你引发了一个想法,我有正确的代码,但在错误的地方!由于这是一个子视图,我没有在正确的位置执行代码....代码现在已被放置在父视图中