非常棒的问题。我为你的问题尝试了一个样本。我得到了解决方案,它工作正常。
你在你的代码犯的错误是
首先你
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