无法将rightBarButton添加到UINavigationBar

时间:2013-06-11 07:50:58

标签: ios objective-c uinavigationcontroller uinavigationbar

我已将UINavigationController隐藏到我的pop&推送需求,现在我想向UINavigationBar添加自定义背景图像和一些自定义按钮。 我已经读过我可以在appdelegate中做到这一点(自iOS 5开始),但是我想将它保留在UINavigationController子类中以备将来使用。

我尝试过这样的事情:

-(void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightbutton setFrame:CGRectMake(280, 0, 56, 39)];
    [rightbutton setImage:[UIImage imageNamed:@"top.png"] forState:UIControlStateNormal];
    [rightbutton addTarget:self action:@selector(popMePlease) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton=[[UIBarButtonItem alloc] initWithCustomView:rightbutton];
    [[self  navigationItem] setRightBarButtonItem:rightBarButton];
}

但我看不到右边的巴顿。我不知道viewDidLoad是否适合放入。

3 个答案:

答案 0 :(得分:0)

在您的代码按钮中,x位置从280开始。它应该接近0。

替换以下行

[rightbutton setFrame:CGRectMake(280, 0, 56, 39)];

[rightbutton setFrame:CGRectMake(0, 0, 56, 39)];

答案 1 :(得分:0)

试试这个工作正常。

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(0, 0, 40, 40);
[myButton setBackgroundImage:[UIImage imageNamed:@"imTitleBG.png"] forState:UIControlStateNormal];
UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]initWithCustomView:myButton];
self.navigationItem.rightBarButtonItem = rightBtn;

答案 2 :(得分:-1)

试试这段代码

 UIBarButtonItem *btn = [[UIBarButtonItem alloc]
                       initWithCustomView:myButton];
        self.navigationItem.rightBarButtonItem=btn;

-(void)Action
{

// Do what you want here 

}

尝试此代码可能对您有所帮助......