非常棒的問題。我爲你的問題嘗試了一個樣本。我得到了解決方案,它工作正常。
你在你的代碼犯的錯誤是
首先你
let refreshButton = UIBarButtonItem(title: "Refresh", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(FollowVC.refresh))
是wrong.You必須使用或寫
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem, target: AnyObject?, action:Selector)
第二你使用UIBarButtonItemStyle.Plain。如果你想刷新按鈕,你必須設置UIBarButtonSystemItem.Refresh。
SWIFT
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 64)) // set frame here
//set the background color
navigationBar.backgroundColor = UIColor.whiteColor()
navigationBar.delegate = self;
// Create a navigation item with a title
let navigationItem = UINavigationItem()
navigationItem.title = "Title" //If you want to set a tilte set here.Whatever you want set here.
// Create button for navigation item with refresh
let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "actionRefresh:")
// I set refreshButton for the navigation item
navigationItem.leftBarButtonItem = refreshButton
// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]
// Make the navigation bar a subview of the current view controller
self.view.addSubview(navigationBar)
}
#pragma action method
func actionRefresh(sender: UIBarButtonItem)
{
print("The action button is refreshed")
}
打印語句
The action button is refreshed
目標C
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
navbar.backgroundColor = [UIColor whiteColor];
navbar.delegate = self;
UINavigationItem * navItem = [[UINavigationItem alloc] init];
navItem.title = @"Title"; //Set Title Here Wahtever You Want Here
UIBarButtonItem *buttonRefresh = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:@selector(actionRefresh:)];
navItem.leftBarButtonItem = buttonRefresh;
navbar.items = @[navItem];
[self.view addSubview:navbar];
}
該聲明的NSLog是
The button action refresh is performed
見截圖刷新按鈕
好的解決辦法
Add Default Icons to Navigation Bar
Navigation Bar Item Programmatically
Adding Navigation Bar item Programmatically
好的問題,甚至已經問過。 – user3182143
檢查我的更新答案爲目標c和swift。 – user3182143