我试图在导航 Controller 内的 TableViewController 底部显示工具栏项。我用 Swift 编写了这段代码。
我使用 Xcode 默认的主从模板来创建项目,并在 MasterTableViewController 的 ViewDidLoad 方法中编写了以下代码。
请帮我解决这个问题。
请在下面找到代码片段。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.addToolBar();
}
func addToolBar ()->Void {
self.hidesBottomBarWhenPushed = false
var toolBarItems = NSMutableArray()
var systemButton1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: nil, action: nil)
toolBarItems.addObject(systemButton1)
var systemButton2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
toolBarItems.addObject(systemButton2)
var systemButton3 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Trash, target: nil, action: nil)
toolBarItems.addObject(systemButton3)
self.navigationController?.toolbarHidden = false
self.setToolbarItems(toolbarItems, animated: true)
//self.navigationController?.toolbarItems = toolbarItems;
}
但有趣的是,用 Objective-C 编写的相同代码可以工作并在底部显示带有两个项目的工具栏
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
[self addToolbar];
}
-(void) addToolbar
{
self.hidesBottomBarWhenPushed = NO;
NSMutableArray *items = [[NSMutableArray alloc] init];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:nil action:nil];
[items addObject:item1];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:item2];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:nil action:nil];
[items addObject:item3];
self.navigationController.toolbarHidden = NO;
// self.navigationController.toolbarItems = items;
//
[self setToolbarItems:items animated:YES];
}
最佳答案
您的代码中有一个小错字。我为您强调了不同之处:
var toolBarItems = NSMutableArray()
// ^
// [...]
self.setToolbarItems(toolbarItems, animated: true)
// ^
您的代码基本上是这样做的(带有动画):
self.toolbarItems = self.toolbarItems
您将 toolbarItems 数组设置为当前的 toolbarItems 数组,该数组为空。
当您使用 self.setToolbarItems(toolBarItems, animated: true)
时,它将起作用。
关于ios - 无法使用 Swift 在 NavigationController 中显示工具栏项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490014/