我正在尝试在导航控制器内部的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];
}
答案 0 :(得分:2)
你的代码中有一个小错字。我强调了你的不同之处:
var toolBarItems = NSMutableArray()
// ^
// [...]
self.setToolbarItems(toolbarItems, animated: true)
// ^
你的代码基本上是这样的(带动画):
self.toolbarItems = self.toolbarItems
您将toolbarItems数组设置为当前toolbarItems数组,该数组为空。
当您使用self.setToolbarItems(toolBarItems, animated: true)
时,它会起作用。
答案 1 :(得分:1)
使用NSMutableArray给了我错误,下面的代码对我有用
func setUpToolbar(){
var toolBarItems = [UIBarButtonItem]()
let systemButton1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: nil, action: nil)
toolBarItems.append(systemButton1)
let systemButton2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
toolBarItems.append(systemButton2)
let systemButton3 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Trash, target: nil, action: nil)
toolBarItems.append(systemButton3)
self.setToolbarItems(toolBarItems, animated: true)
self.navigationController?.toolbarHidden = false
}