答案 0 :(得分:7)
精湛的问题。我为你的问题试了一个样品。我得到了解决方案并且工作正常。
你在编码中犯了什么错误
首先你的
let refreshButton = UIBarButtonItem(title: "Refresh", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(FollowVC.refresh))
是错误的。你必须使用或写
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem, target: AnyObject?, action:Selector)
其次你使用了 UIBarButtonItemStyle.Plain 。如果你想要刷新按钮,你必须设置 UIBarButtonSystemItem.Refresh 。
<强> SWIFT 强>
override func viewDidLoad()
{
// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.view.frame.size.width, height: 64))) // set frame here
//set the background color
navigationBar.backgroundColor = UIColor.white
navigationBar.delegate = self as? UINavigationBarDelegate;
// 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: Selector(("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
答案 1 :(得分:2)
您应该使用.Plain
而不是.Refresh
。
let refreshButton = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: #selector(FollowVC.refresh))
此外,您应该使用init(barButtonSystemItem:target:action:)
代替init(title:style:target:action:)
。