2010-08-16 76 views

回答

32
UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark]; 
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn]; 
+0

輝煌,感謝里納。我已經將它標記爲已接受的答案,但是如果你願意原諒我的臉頰,請問如何讓信息按鈕左移五個像素左右?添加它作爲正確的酒吧按鈕項目意味着它被擠壓在屏幕的右側。 – 2010-08-16 10:50:49

+1

使用'leftBarButtonItem'屬性,你可以在左邊設置 self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn]; – Reena 2010-08-16 10:57:58

+1

對不起Reena。我希望它作爲正確的按鈕項目,我只是想在右側添加一點點空間(從而將右邊的按鈕5px帶到左邊)。那可能嗎? – 2010-08-16 11:17:35

5

這是一個非常好看的解決方案,我認爲它涵蓋了人們在上述評論中提到的所有要點。與接受的答案類似,但此方法包括額外的間距(通過修改框架),以便按鈕不會撞到右邊緣。

// Create the info button 
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight]; 

// Adjust the frame by adding an addition 10 points to its width so the button is padded nicely 
infoButton.frame = CGRectMake(infoButton.frame.origin.x, infoButton.frame.origin.y, infoButton.frame.size.width + 10.0, infoButton.frame.size.height); 

// Hook the button up to an action 
[infoButton addTarget:self action:@selector(showInfoScreen) forControlEvents:UIControlEventTouchUpInside]; 

// Add the button to the nav bar 
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton]; 

// Also make sure to add a showInfoScreen method to your class! 
+0

歡呼凱爾完美地工作 – adamteale 2014-04-13 23:10:09

0

我想這將是更完整的響應,它應該在任何情況下幫助:

-(void)viewDidLoad{ 

    //Set Navigation Bar 
    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)]; 

    //Set title if needed 
    UINavigationItem * navTitle = [[UINavigationItem alloc] init]; 
    navTitle.title = @"Title"; 

    //Here you create info button and customize it 
    UIButton * tempButton = [UIButton buttonWithType:UIButtonTypeInfoLight]; 

    //Add selector to info button 
    [tempButton addTarget:self action:@selector(infoButtonClicked) forControlEvents:UIControlEventTouchUpInside]; 

    UIBarButtonItem * infoButton = [[UIBarButtonItem alloc] initWithCustomView:tempButton]; 

    //In this case your button will be on the right side 
    navTitle.rightBarButtonItem = infoButton; 

    //Add NavigationBar on main view 
    navBar.items = @[navTitle]; 
    [self.view addSubview:navBar]; 

} 
1

對於斯威夫特:

func addRightNavigationBarInfoButton() { 
    let button = UIButton(type: .infoDark) 
    button.addTarget(self, action: #selector(self.showInfoScreen), for: .touchUpInside) 
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button) 
} 

@objc func showInfoScreen() { 
    // info bar button pressed 
}