简体   繁体   English

无法将rightBarButton添加到UINavigationBar

[英]Can't add rightBarButton to UINavigationBar

I've subclassed UINavigationController to my pop & push needs and now I want to add a custom background image and some custom buttons to the UINavigationBar . 我已经将UINavigationController细分为我的弹出和推送需求,现在我想向UINavigationBar添加自定义背景图像和一些自定义按钮。 I've read that I can do it (since iOS 5) inside the appdelegate but I'd like to keep it inside the UINavigationController subclass for future use. 我已经读到,我可以在appdelegate中执行此操作(自iOS 5起),但我想将其保留在UINavigationController子类中,以备将来使用。

I've tried doing something like this: 我尝试做这样的事情:

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

But I can't see the rightBarButton. 但是我看不到rightBarButton。 I don't know if viewDidLoad is the place to put it in. 我不知道viewDidLoad是否是放置它的地方。

In your code button x position starts from 280 . 在您的代码按钮x位置从280开始。 It shoud be near to 0. 应该接近0。

Replace following line 替换以下行

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

with

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

Try this it's working fine. 试试这个,它工作正常。

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;

try this code 试试这个代码

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

-(void)Action
{

// Do what you want here 

}

try this code might be helpful to you... 试试这个代码可能对您有帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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